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