11

I'm using the code below to write into a text file

String content = "I Love Java";
Files.write(Paths.get(gg), (content + "\n").getBytes(UTF_8),StandardOpenOption.CREATE,StandardOpenOption.APPEND);

After 3 times of run, the text is saved into the the text as :

I Love JavaI Love JavaI Love Java

But, I want the text in the text file looks like:

I Love Java 
I Love Java
I Love Java

Any help please ?

davidxxx
  • 125,838
  • 23
  • 214
  • 215
FSm
  • 2,017
  • 7
  • 29
  • 55
  • 2
    Windows? `\r\n`. Of, even better, use other [`Files.write`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-java.lang.Iterable-java.nio.charset.Charset-java.nio.file.OpenOption...-) that specifically writes lines to a file. – Boris the Spider Jan 22 '17 at 09:50

1 Answers1

26

You should avoid specific new line separators such as "\n" or "\r\n" that depends on the OS and favor the use of the System.lineSeparator() constant that applies at runtime the separator of the OS on which the JVM runs.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • 18
    `Files.write(Paths.get(gg), (content + System.lineSeparator()).getBytes(UTF_8),StandardOpenOption.CREATE,StandardOpenOption.APPEND);` – davidxxx Jan 22 '17 at 10:00