如何在 java 中将附加选项和 StandardCharsets/Encoding 设置为 BufferedWriter?

How to set append options and StandardCharsets/Encoding to BufferedWriter in java?

我是 java 编程新手,正在寻找使用 java 编写和附加文件内容的选项。

以下 C# 选项的类似选项。

File.WriteAllText(string path, string contents, Encoding encoding);
File.AppendAllText(string path, string contents, Encoding encoding);

我虽然要使用 BufferedWriter,它可以选择为 FileWriter(字符串路径,布尔附加)传递 true/false,但我没有提供编码的选项。

try (FileWriter fw = new FileWriter(path, false);
    BufferedWriter bw = new BufferedWriter(fw)) {
    bw.write("appending text into file");
}

如果我用 Files.newBufferedWriter 初始化 BufferedWriter,我可以提供 StandardCharsets,但它没有附加选项以防现有文件。

try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(path), StandardCharsets.UTF_8)) {
    bw.write("test");
    bw.append("append test");
}

是否可以同时定义两个选项(附加选项和 StandardCharsets)?

是的。如果你查看 Files class 实现,有一个方法如下:

public static BufferedWriter newBufferedWriter(Path path, Charset cs, OpenOption... options)

所以你可以调用类似

的方法
BufferedWriter bw = Files.newBufferedWriter(Paths.get(path), StandardCharsets.UTF_8, 
                    StandardOpenOption.CREATE, StandardOpenOption.APPEND)

如果您使用像 Intellij 这样的 IDE,它会建议您可以调用哪些 public 方法。

您可以尝试 java.nio 以便将内容附加到现有文件(如果您使用的是 Java 7 或更高版本),也许您可​​以这样做:

List<String> newContent = getNewContent(...); // Here you get the lines you want to add
Files.write(myFile, newContent, UTF_8, APPEND, CREATE);

导入需要由以下人员完成:

java.nio.charset.StandardCharsets.UTF_8, java.nio.file.StandardOpenOption.APPEND, java.nio.file.StandardOpenOption.CREATE

或者您可以尝试使用 Guava:

File myFile = new File("/Users/home/dev/log.txt");
String newContent = "This is new content";
Files.append(newContent, myFile, Charsets.UTF_8);