Line separator in Java N/IO?

后端 未结 3 1431
[愿得一人]
[愿得一人] 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 06:56

    Complementing to @Tunaki, if you want two lines, only insert another line:

    String test = "ABC" + System.lineSeparator() + System.lineSeparator() + "DEF";

    0 讨论(0)
  • 2021-01-29 07:10

    Beginning with Java 7, you should use System.lineSeparator() instead of hard coding \n, since the line separator really depends on which machine the code will run.

    public static void main(String args[]) throws IOException {
        final Path PATH = Paths.get("test.txt");
        String test = "ABC" + System.lineSeparator() + "DEF";
        Files.write(PATH, test.getBytes());
    }
    

    If you are still using Java 6 or older, the same is achieved with System.getProperty("line.separator") (see Oracle docs).

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题