Line separator in Java N/IO?

后端 未结 3 1436
[愿得一人]
[愿得一人] 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

    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).

提交回复
热议问题