如何在Java中覆盖文件内容而不删除现有内容?

Pri*_*hrm 3 java

我不想追加也不想截断现有数据。我想覆盖现有数据。例如,以下代码使 test.txt 文件包含“hello”,但我希望该文件包含“hello6789”。

try(
   FileWriter fw = new FileWriter("test.txt"); ){
   fw.write("123456789");
}    
try(
   FileWriter fw = new FileWriter("test.txt"); ){
   fw.write("hello");
}
Run Code Online (Sandbox Code Playgroud)

是否可以?

Abr*_*bra 7

我建议使用Java 7 中添加的NIO.2。
(请注意,下面的代码也使用了try-with-resources。)

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class Proj2 {

    public static void main(String[] args) {
        Path path = Paths.get("test.txt");
        try (BufferedWriter bw = Files.newBufferedWriter(path,
                                                         StandardOpenOption.CREATE,
                                                         StandardOpenOption.WRITE)) {
            bw.write("123456789");
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
        try (BufferedWriter bw = Files.newBufferedWriter(path,
                                                         StandardOpenOption.CREATE,
                                                         StandardOpenOption.WRITE)) {
            bw.write("hello");
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

运行上述代码后文件test.txt的内容:

hello6789
Run Code Online (Sandbox Code Playgroud)

另请参阅javadoc以获取 [enum] StandardOpenOption

  • 但应该注意的是,如果应用程序……或操作系统……在不合时宜的时刻终止,文件的就地重写*可能*会导致文件损坏。 (3认同)