This is one of those things that seems obvious until you’re debugging cross-platform output issues. System.getProperty("line.separator") gives you the OS-specific newline — \r\n on Windows, \n on Unix. Java 7 added System.lineSeparator() as a cleaner shorthand. The BufferedWriter.newLine() approach is the best practice when writing to files.
1
| System.getProperty("line.separator");
|
- [Update For] Java 7 and above
1
2
3
4
5
6
7
8
9
| StringWriter stringWriter = new StringWriter();
BufferedWriter bufferedWriter = new BufferedWriter(stringWriter);
final String data = "hello";
bufferedWriter.write(data, 0, data.length());
bufferedWriter.newLine();
bufferedWriter.newLine();
bufferedWriter.write(data, 0, data.length());
bufferedWriter.flush();
System.out.print(stringWriter.getBuffer());
|
- if commons-lang is already being used in the project
1
| SystemUtils.LINE_SEPARATOR
|