Java PrintWriter 文件覆盖

Java PrintWriter File Overwrite

我想使用 UTF-16 写入文件,所以我使用 PrintWriter(file,"UTF-16"),但它会删除文件中的所有内容,我可以使用 FileWriter(file,true),但是那么它就不会在 UTF-16 中,并且显然没有像 PrintWriter(Writer,Charset,boolean append);

这样的 PrintWriter 的构造函数

我该怎么办?

使用带有 UTF-16 字符集的 OutputStreamWriter,包装使用 append=true 打开的 FileOutputStream。备选方案,使用 Files.newBufferedWriter:

try (Writer writer = Files.newBufferedWriter(
        Paths.of("filename.txt"),
        StandardCharsets.UTF_16,
        StandardOpenOption.APPEND)) {
    ...
}

您可以使用

new PrintWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-16"));

FileWriter 的 JavaDoc 说:

The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

所以你可以这样做:

 Writer writer = new PrintWriter(
     new OutputStreamWriter(
           new FileOutputStream(filename, true),
           StandardCharsets.UTF16));

您可能还想在其中包含 BufferedOutputStream 以获得最高效率。