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
Complementing to @Tunaki, if you want two lines, only insert another line:
String test = "ABC" + System.lineSeparator() + System.lineSeparator() + "DEF";
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).
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.