【发布时间】:2020-11-14 16:31:21
【问题描述】:
我目前正在为大学任务制作一个简单的文本编辑器,并通过用户输入,在现有文件上进行基本操作(切换行位置或单词位置)。
我的程序由一个包含所有逻辑的 FileManipulator 类和一个 GUI 类(main 所在的地方)组成
public class FileManipulator {
File file;//current file
BufferedReader fileReader; //Reader for the file
String currentDirectory; //Always verified due to setDirectory() validation
public FileManipulator() throws IOException{ ...;}
public void loadFile() throws IOException{
if(this.fileReader != null) {
this.fileReader.close();
}
this.file = new File(this.currentDirectory);
//if there isn't a txt file, ask user if he wants to create one
if(!file.exists()) { //logic for creating a new file}
//After we are sure a file exists in this directory, we init the fileReader
this.fileReader = new BufferedReader(new FileReader(this.file));
this.fileReader.mark(READ_AHEAD_LIMIT);
}
public void switchLines(int line1, int line2) throws ArrayIndexOutOfBoundsException, IOException {
//Logic about switching the lines here
//Writing to the file
writeToFile(fileContents);
}
//Will open a writer, write to the file and close the writer
private void writeToFile(ArrayList<String> listToPrint) throws IOException{
StringBuilder tempList = new StringBuilder();
for (String s : listToPrint) {
tempList.append(s);
tempList.append('\n');
}
FileWriter fileWriter = new FileWriter(this.file);
fileWriter.append(tempList);
fileWriter.close();
/* In this function, we make changes to the file, however, when using getFileText()
* the changes written in the file aren't noticed and the old file is returned
*/
}
//Problematic function
public String getFileText() throws IOException{
fileReader.reset();
StringBuilder finalText = new StringBuilder();
String temp;
while((temp = fileReader.readLine()) != null) {
finalText.append(temp);
finalText.append('\n');
}
return finalText.toString();
}
对文件进行更改并保存后,我的 BufferedReader 没有更新。它仍然会读取更改前的内容。
当我使用 loadFile 方法并重新加载同一个文件时,缓冲阅读器会关闭并重新打开,因此文件的内容会更新,但是每次我使用缓冲阅读器时打开和关闭它并不是最优雅的解决方案。
我也想过拥有一个文件内容的 ArrayList 并仅在关闭程序时更新它,但如果我错过了一个简单的修复,那将是一个不必要的练习。
【问题讨论】:
-
阅读文件后确保关闭它。您可能无法在文件仍处于打开状态时对其进行写入。
-
BufferedReader值得注意的部分是 Buffered 部分。重新设置并再次读取时,您正在读取 缓冲区,而不是文件。您必须关闭并重新打开才能再次读取文件。
标签: java file bufferedreader