我有一个filewriter方法,它只在我关闭文件时输出到文件



String 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();
}
}
}

这个方法是为了更改文件中的某一行,该方法本身在运行时可以工作,但它只在我关闭程序时更改该行,也就是它关闭编写器时,我查找了它,并在代码的早期添加了writter.flush((,看看这是否可行,但我仍然有同样的问题

您正在尝试读取和写入同一个文件。您不能同时执行这两个操作,因为文件将被锁定。关闭读卡器,然后执行写入操作。

最新更新