Course contentsShow
← Java
Lesson 1984 of 2,87040. File I/O: Character StreamsFree lesson

newLine: Platform-Independent Line Separators

Learn to use newLine() to write line separators that adapt to the current platform (Windows, Unix, Mac).

newLine: Platform-Independent Line Separators

You'll learn how to write line breaks that work correctly on any operating system using BufferedWriter's newLine() method.

The Cross-Platform Line Break Challenge

Different operating systems use different character sequences to mark the end of a line:

  • Windows: \r\n (carriage return + line feed)
  • Unix/Linux: \n (line feed only)
  • Old Mac: \r (carriage return only)

If you hard-code "\n" in your Java program and run it on Windows, text editors might not display line breaks correctly. Your nicely formatted file could appear as one long line!

The newLine() Solution

BufferedWriter provides the newLine() method that automatically writes the appropriate line separator for the current platform:

BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));

writer.write("First line");
writer.newLine();  // Writes \r\n on Windows, \n on Unix
writer.write("Second line");
writer.newLine();
writer.write("Third line");

writer.close();

Think of newLine() as a multilingual translator for line breaks—it speaks the native "dialect" of whatever operating system your code runs on.

Why Not Just Use write("\n")?

You could write writer.write("\n") or even writer.write(System.lineSeparator()), but newLine() is clearer in intent and specifically designed for this purpose. It makes your code self-documenting: "I'm ending a line here, properly."

When It Matters Most

Use newLine() when:

  • Your files will be opened in platform-specific text editors
  • You're generating configuration files, logs, or CSV files
  • Cross-platform compatibility is important

Key Takeaway: BufferedWriter.newLine() writes the correct line separator for the current platform automatically, ensuring your text files display properly on Windows, Unix, and Mac systems without hard-coding platform-specific escape sequences.