第二次将“something”这个词添加到文件中并打印“atext has added”但它将其视为空文件....什么..public class ReadFile {
public ReadFile() {
}
public boolean readFile() {
boolean success = false;
String file_name = "source/text.txt";
try {
FileReader file = new FileReader(file_name);
BufferedReader read = new BufferedReader(file);
BufferedWriter bf = new BufferedWriter(new FileWriter (file_name));
if (read.readLine() != null) {
bf.append("something");
System.out.println("a text has been added!!");
} else {
bf.append(file_name);
System.out.println("File updated");
}
read.close();
bf.close();
success = true;
} catch(IOException e) {
e.getMessage();
}
return success;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ReadFile rf = new ReadFile();
rf.readFile();
}}当文件不为空时,应该在EOF中添加“something”
3 回答
慕村225694
TA贡献1880条经验 获得超4个赞
您需要以附加模式打开文件,否则当FileWriter打开文件时它将被清空:
BufferedWriter bf = new BufferedWriter(new FileWriter (file_name, true));
神不在的星期二
TA贡献1963条经验 获得超6个赞
这里需要进行一些更改
您需要以追加模式打开文件进行写入
在将数据附加到文件以便读取之后,需要调用flush()
你需要一个循环,至少如果你想在同一个运行中发生一切
请注意,我在这里使用了一个无限循环,这是危险的,因此有改进的余地。捕获异常时我还添加了println
try { FileReader file = new FileReader(file_name); BufferedReader read = new BufferedReader(file); BufferedWriter bf = new BufferedWriter(new FileWriter (file_name, true)); while(true) { if(read.readLine() != null) { bf.append("something"); System.out.println("a text has been added!!"); break; } else { bf.append(file_name); bf.flush(); System.out.println("File updated"); } } read.close(); bf.close(); success = true;} catch(IOException e) { System.out.println(e.getMessage());}
添加回答
举报
0/150
提交
取消