我正在寻找一种简单、安全的解决方案,可以使用特定的Charset cs
在Java 8中将文本追加到现有文件中。我在这里找到的解决方案处理了标准的Charset
,但在我的情况下不可行。
使用重载版本的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);
Path path = Paths.get("...");
Charset charset = StandardCharsets.UTF_8;
List<String> list = Collections.singletonList("...");
Files.write(path, charset, list, StandardOpenOption.APPEND);
根据你所提到的问题中被接受的答案:
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
}
open()
函数,有助于理解这些内容。最终,Java只能提供对系统函数的包装器。如果Java不够强大,了解通过JNA可以回退到什么也是很有用的。 - the8472