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

Line Terminator Handling Across Platforms

Understand how readLine() handles \n, \r, and \r\n line terminators transparently across different operating systems.

Line Terminator Handling Across Platforms

What you'll learn: How readLine() seamlessly handles different line-ending conventions across Windows, Unix, and Mac systems.

The Cross-Platform Line Ending Problem

Different operating systems use different characters to mark the end of a line in text files:

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

If you had to manually detect which line terminator your file uses, text processing would be a nightmare. Every file from a different OS would require special handling.

BufferedReader's Transparent Solution

The readLine() method in BufferedReader automatically recognizes and handles all three line terminator conventions:

BufferedReader reader = new BufferedReader(new FileReader("crossplatform.txt"));
String line = reader.readLine(); // works regardless of line endings!

When readLine() reads characters, it stops at any of these terminators: \n, \r, or \r\n. Crucially, it strips the terminator characters from the returned string—you only get the actual text content of the line.

Why This Matters

Imagine reading a file created on Windows (with \r\n endings) on a Linux machine. Without automatic handling, you'd get stray \r characters in your strings. readLine() handles this transparently—your code works identically on all platforms without modification.

Analogy: Think of readLine() as a multilingual translator who understands that "Hello," "Bonjour," and "Hola" all mean the same greeting. It converts any line ending dialect into a standard format: just the line content, no terminators attached.

Key Takeaway: readLine() automatically detects and removes \n, \r, and \r\n line terminators, making your text-reading code platform-independent without any extra effort.