Home  >  Q&A  >  body text

Java:使用NIO2写文件时如何追加文件内容呢?

通过以下方式可以写文件

List<String> list = new ArrayList<String>();
list.add("第一行");
list.add("第二行");
list.add("第三行");
 
Path path = Paths.get("E:" + File.separator + "demo.txt");
Files.write(path, list, Charset.forName("UTF-8"));   

但如果想每次执行都追加内容该怎么办呢?

高洛峰高洛峰2760 days ago475

reply all(1)I'll reply

  • 黄舟

    黄舟2017-04-17 17:58:19

    First of all, it is better to write the code above like this (see):

    Path path = Paths.get("E:", "demo.txt");
    Files.write(path, list, StandardCharsets.UTF_8);

    As for appending, just use the APPEND option of StandardOpenOption:

    Files.write(path, list, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

    reply
    0
  • Cancelreply