(java)对文件进行更改后如何更新bufferedreader

j91ykkif  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(498)

我目前正在为一个大学任务制作一个简单的文本编辑器,通过用户输入,在一个已经存在的文件上,我正在进行基本的操作(切换行位置或单词位置)。
我的程序由一个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,并且只在关闭程序时更新它,但是如果我错过了一个简单的修复,那将是一个不必要的练习。

vq8itlhq

vq8itlhq1#

bufferedreader就是这样工作的。 reset 以及 mark 都是在记忆中完成的。
有许多解决方案:
嘿,不管怎样,你已经承诺要把整件事都存储在内存里了。为什么不将文本文件表示为 BufferedReader 但作为一个 String 或者 List<String> 或者诸如此类,让更新代码更新它,然后将其写入磁盘,除了应用程序启动时,没有读取代码?为什么要把磁盘当作中间人呢?
使用filechannel、randomaccessfile或其他对文件的抽象,特别是那些对实际从磁盘读取有更好支持的文件。请注意,在写入时也需要这样做:在许多操作系统上,“从头开始将所有这些内容写入此文件”实际上会生成一个新文件,并且任何打开的文件句柄仍然指向文件系统中不再可访问的旧文件。
只是。。关闭该文件读取器并再次打开它,或者甚至设置一个布尔标志,让读代码知道写代码做了更改,并且只在标志为“true”时才这样做(当然,然后将其设置为false)。

相关问题