我有一个只能在关闭文件时输入文件的文件编写器方法

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( )之前在代码中查看是否可行,但我仍然遇到相同的问题

xtc168 回答:我有一个只能在关闭文件时输入文件的文件编写器方法

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

本文链接:https://www.f2er.com/3055890.html

大家都在问