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

ozxc1zmp  于 12个月前  发布在  Java
关注(0)|答案(1)|浏览(130)

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

try(
   FileWriter fw = new FileWriter("test.txt"); ){
   fw.write("123456789");
}    
try(
   FileWriter fw = new FileWriter("test.txt"); ){
   fw.write("hello");
}

字符串
有可能吗?

inkz8wg9

inkz8wg91#

我建议使用Java 7中添加的NIO.2
(Note下面的代码也使用了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();
        }
    }
}

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

hello6789


另请参考 javadoc for [enum] StandardOpenOption

相关问题