Line separator in Java N/IO?

后端 未结 3 1456
[愿得一人]
[愿得一人] 2021-01-29 06:49

How do I insert new line when writing to a txt file using java.nio.file ? The following code produces a txt file with one line ABCDEF, instead of two s

3条回答
  •  一向
    一向 (楼主)
    2021-01-29 07:10

    Other options to use the system line separator:

    Use another overload of Files.write which expects an Iterable of strings (CharSequence, to be exact) and writes each of them on its own line using the system line separator. This is most helpful if you already store the lines in a collection.

    Files.write(PATH, Arrays.asList("ABC","DEF"),StandardCharsets.UTF_8);
    

    (It's better to specify the character set rather than rely on the default, which is what happens when using String.getBytes() without a character set).

    Or use String.format:

    String test = String.format("ABC%nDEF");
    

    Formatter (which String.format uses) interprets %n as the system line separator.

    This approach is backward-compatible all the way back to Java 1.5. But of course, the Files class did not exist before Java 7.

提交回复
热议问题