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();
}
}
}
此方法旨在更改文件的特定行,该方法在运行时本身会起作用,但仅在我关闭程序(即关闭编写器时)时才更改该行,然后查找并添加writer.flush( )之前在代码中查看是否可行,但我仍然遇到相同的问题