java我有一个filewriter方法,它只在我关闭文件时输出到该文件
字符串filePath=“Seat”
static void modifyFile(String filePath, String oldString, String newString) {
File fileToBeModified = new File(filePath);
String oldContent = "";
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(fileToBeModified));
//Reading all the lines of input text file into oldContent
String line = reader.readLine();
while (line != null) {
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
//Replacing oldString with newString in the oldContent
String newContent = oldContent.replaceAll(oldString, newString);
//Rewriting the input text file with newContent
writer = new BufferedWriter(new FileWriter(fileToBeModified));
writer.write(newContent);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//Closing the resources
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
此方法用于更改文件中的某一行。该方法本身在运行时可以工作,但它仅在关闭程序时更改该行,即在关闭writer时,我查找该行并添加writer。在前面的代码中使用flush()来查看这是否有效,但我仍然有同样的问题
# 1 楼答案
您正在尝试读取和写入同一文件。 不能同时执行这两个操作,因为文件将被锁定。关闭读卡器,然后执行写入操作