Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我有一个filewriter方法,它只在我关闭文件时输出到该文件_Java_Filewriter - Fatal编程技术网

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

Java 我有一个filewriter方法,它只在我关闭文件时输出到该文件,java,filewriter,Java,Filewriter,字符串filePath=“Seat” 此方法用于更改文件中的某一行。方法本身在运行时可以工作,但它仅在关闭程序时更改该行,也就是在关闭writer时,我查找该行并添加writer.flush()在前面的代码中,我想看看这是否可行,但我仍然有相同的问题您正在尝试读取和写入同一个文件。 不能同时执行这两个操作,因为文件将被锁定。关闭读卡器,然后执行写入操作。您是否尝试在writer.flush()之后添加writer.close()?是的,尝试将其移动到那里,但它不起作用,并尝试使用两个writer

字符串filePath=“Seat”


此方法用于更改文件中的某一行。方法本身在运行时可以工作,但它仅在关闭程序时更改该行,也就是在关闭writer时,我查找该行并添加writer.flush()在前面的代码中,我想看看这是否可行,但我仍然有相同的问题

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

您是否尝试在
writer.flush()
之后添加
writer.close()
?是的,尝试将其移动到那里,但它不起作用,并尝试使用两个writer.close(),但它只在程序停止运行时写入文件,与问题无关,但是对于Java7和更高版本来说,这是处理资源关闭的首选方式。哈哈,我甚至没有看到这一点。OP代码的第二行。
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();
        }
    }
}