我想将字符串的内容保存到Java文件中。 字符串“sttr”的内容逐行从文本文件中读取。 当我运行代码时,我得到了正确的输出但是当我尝试将内容写入Java文件时,我只得到一行。代码:
String content = " test ";
String content1 = "test01";
//read text file line by line
try {
FileInputStream fstream = new FileInputStream("E:\\test\\myfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
String sttr ;
while ((strLine = br.readLine()) != null) {
sttr = strLine;
System.out.println(content+sttr+content1);
File file = new File("E:/test/output.java");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
//bw.write(content);
bw.write(content+sttr+content1);
//bw.write(content1);
//bw.close();
//System.out.println("Done");
}
}
catch (Exception e) { //Catch exception if any
System.err.println("Error: " + e.getMessage());
}
答案 0 :(得分:1)
不要每次都重新创建BufferedWriter,在循环外执行一次。否则,它将删除文件的内容。
File file = new File("E:/test/output.java");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
String strLine;
String sttr ;
while ((strLine = br.readLine()) != null) {
// [...]