java如何写入文件

发布网友 发布时间:2022-04-25 05:23

我来回答

4个回答

热心网友 时间:2023-10-29 17:51

package filewriter;  
  
import java.io.FileWriter;  
import java.io.IOException;  
  
public class IOExceptionDemo {  
  
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");  
    public static void main(String[] args) {  
  
        FileWriter fw = null;  
        try {  
            fw = new FileWriter("k:\\Demo.txt", true);  
            fw.write("hello" + LINE_SEPARATOR + "world!");  
        } catch (Exception e) {  
            System.out.println(e.toString());  
        } finally {  
            if (fw != null)  
                try {  
                    fw.close();  
                } catch (IOException e) {  
                    throw new RuntimeException("关闭失败!");  
                }  
        }  
    }  
}

热心网友 时间:2023-10-29 17:51

乞儿群 雾灵四死五霸七要,讨论

热心网友 时间:2023-10-29 17:51

如果是写一般的txt文件
可以直接用PrintWriter pw = new PrinterWriter(new File("1.txt"));
pw.println("hello");

热心网友 时间:2023-10-29 17:52

package generatesql;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Practice {
/**
* @param args
*/
public static void main(String[] args) throws Exception {

File fileReader = new File("C:/Users/Administrator/Desktop/" +"1111.txt");
File fileWriter = new File("C:/Users/Administrator/Desktop/" +"1111.sql");

StringBuffer sb = getDate(fileReader); //读取字符串

if(sb!=null && sb.length()>0){
if(!fileWriter.exists()){
fileWriter.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(fileWriter));
bw.write(sb.toString());
bw.flush();
bw.close();
}
}
public static StringBuffer getDate(File fileReader1){
StringBuffer sb = new StringBuffer();
if(!fileReader1.exists()){
return sb;
}

BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(fileReader1));
String temp = "";
while((temp=br.readLine())!=null){
System.out.println(temp);
String arr[] = temp.split("-");
sb.append("update table set key ='"+arr[0]+"' and key1='"+arr[1]+"';\n");
}
br.close();
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb;
}

}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com