How to append text to file in Java 8 using specifi

2019-04-20 01:44发布

I'm looking for an easy and save solution to append text to a existing file in Java 8 using a specified Charset cs. The solution which I found here deals with the standard Charset which is a no-go in my situation.

4条回答
SAY GOODBYE
2楼-- · 2019-04-20 02:14

One way it to use the overloaded version of Files.write that accepts a Charset:

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);
查看更多
Explosion°爆炸
3楼-- · 2019-04-20 02:36

Based on the accepted answer in the question you pointed at:

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
}
查看更多
看我几分像从前
4楼-- · 2019-04-20 02:37

You can use append method from Guava Class Files. Also, you can take a look to java.nio.charset.Charset.

查看更多
啃猪蹄的小仙女
5楼-- · 2019-04-20 02:40
Path path = Paths.get("...");
Charset charset = StandardCharsets.UTF_8;
List<String> list = Collections.singletonList("...");
Files.write(path, charset, list, StandardOpenOption.APPEND);
查看更多
登录 后发表回答