如何在Java 8中使用指定的字符集将文本追加到文件中

13

我正在寻找一种简单、安全的解决方案,可以使用特定的Charset cs在Java 8中将文本追加到现有文件中。我在这里找到的解决方案处理了标准的Charset,但在我的情况下不可行。

4个回答

26

使用重载版本的Files.write,该版本接受一个字符集,是一种方法:

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;

List<String> lines = ...;
Files.write(log, lines, UTF_8, APPEND, CREATE);

太好了。我已经在考虑那个函数了,但我不知道有一个OpenOption叫做“APPEND”。我只是读到“options - options specifying how the file is opened”并想:没门,这个函数对我没有帮助。 - principal-ideal-domain
1
了解POSIX API,比如这里的open()函数,有助于理解这些内容。最终,Java只能提供对系统函数的包装器。如果Java不够强大,了解通过JNA可以回退到什么也是很有用的。 - the8472
1
@principal-ideal-domain 你可以参考你提供的链接中的答案https://dev59.com/aXI-5IYBdhLWcg3w483k#29456593。然后你可以查看API,看到有一个重载版本,你可以在其中指定字符集https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#write(java.nio.file.Path,%20java.lang.Iterable,%20java.nio.charset.Charset,%20java.nio.file.OpenOption...)。 - Alexis C.

10
Path path = Paths.get("...");
Charset charset = StandardCharsets.UTF_8;
List<String> list = Collections.singletonList("...");
Files.write(path, charset, list, StandardOpenOption.APPEND);

1
小错误:StandardOpenOption.APPEND - Apostolos

3

根据你所提到的问题中被接受的答案:

try (PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myfile.txt", true), charset)))) {
    out.println("the text");
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接