Skip to lesson

Line endings on Windows and Linux

I'm on:

Showing steps for Windows. They are marked “On Windows” below.

Every line in a text file ends with invisible characters called a line ending. Windows and Linux use different ones, and code that expects one kind can break quietly on a file made with the other.

CRLF versus LF

A line ending is the hidden character or pair of characters that marks where a line of a text file stops: \n (LF) on macOS and Linux, \r\n (CRLF) on Windows.

LF (line feed, \n) ends a line on Linux and macOS. CRLF is the pair \r\n (carriage return, then line feed) that Windows uses. The names come from typewriters: return the carriage, then feed the paper one line.

The text Asha, a line break, Ravi and a line break on two systems. On Windows each line break is two bytes, 0D 0A (CR LF), so the file has 12 bytes. On macOS and Linux each break is one byte, 0A (LF), so the file has 10 bytes.

On Windows

PowerShell can show the bytes of a file. In a file saved by a Windows program, every line ends with 0D 0A.

Windows PowerShell
PS C:\Users\Priya\java-practice> Format-Hex notes.txt           Path: C:\Users\Priya\java-practice\notes.txt

           00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000   41 73 68 61 0D 0A 52 61 76 69 0D 0A              Asha..Ravi..

Example 1 · The same two lines, saved two ways

LineEndingBytesDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class LineEndingBytesDemo {    static String visible(String s) {        return s.replace("\r", "\\r").replace("\n", "\\n");    }
    public static void main(String[] args) throws IOException {        Path win = Path.of("windows.txt");        Path unix = Path.of("linux.txt");        Files.writeString(win, "Asha\r\nRavi\r\n");        Files.writeString(unix, "Asha\nRavi\n");
        System.out.println("windows.txt: " + Files.size(win) + " bytes: " + visible(Files.readString(win)));        System.out.println("linux.txt: " + Files.size(unix) + " bytes: " + visible(Files.readString(unix)));        System.out.println("Same lines? " + Files.readAllLines(win).equals(Files.readAllLines(unix)));
        Files.delete(win);        Files.delete(unix);    }}
Output
windows.txt: 12 bytes: Asha\r\nRavi\r\n
linux.txt: 10 bytes: Asha\nRavi\n
Same lines? true

What this code does

  • visible swaps the invisible characters for the text \r and \n, so you can see them. The Windows file has one extra byte per line: the carriage return.
  • readAllLines gives the same two lines for both files, because it understands both endings and removes them.

So Asha and Ravi on two lines take 10 bytes with LF and 12 bytes with CRLF. The visible text is the same; only the hidden ending differs.

System.lineSeparator and %n

System.lineSeparator() returns the line ending of the computer the program runs on: "\r\n" on Windows, "\n" on macOS and Linux. In printf and String.format, %n is replaced by the same separator.

On Windows

On Windows System.lineSeparator() is \r\n (2 characters), and %n in printf and String.format prints \r\n. A file written with Files.write(path, lines) gets CRLF endings.

Example 2 · System.lineSeparator, %n and Files.write

SeparatorDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;
public class SeparatorDemo {    static String visible(String s) {        return s.replace("\r", "\\r").replace("\n", "\\n");    }
    public static void main(String[] args) throws IOException {        String sep = System.lineSeparator();        System.out.println("lineSeparator: " + visible(sep) + " (" + sep.length() + " chars)");
        String withN = String.format("Name: Asha%nMarks: 86%n");        System.out.println("With %n: " + visible(withN));        System.out.println("With \\n: " + visible("Name: Asha\nMarks: 86\n"));
        Path file = Path.of("report.txt");        Files.write(file, List.of("Name: Asha", "Marks: 86"));        System.out.println("Files.write wrote " + Files.size(file) + " bytes");        Files.delete(file);    }}
Sample output
lineSeparator: \r\n (2 chars)
With %n: Name: Asha\r\nMarks: 86\r\n
With \n: Name: Asha\nMarks: 86\n
Files.write wrote 23 bytes

What this code does

  • This sample run is on Windows. On macOS or Linux the first line says \n (1 chars), %n becomes \n, and Files.write writes 21 bytes.
  • %n, System.lineSeparator(), println and Files.write(path, lines) all follow the computer they run on. A plain "\n" in your String is always just \n.

println and Files.write(path, lines) also use the platform separator. A "\n" you type into a String is always just LF. Choose on purpose: the platform ending for text people read on that computer, a fixed "\n" for files with a set format.

The hidden carriage return bug when splitting on \n

The hidden carriage return bug happens when you split a Windows file on "\n" yourself. The split removes the \n but keeps the \r before it, so every line ends with an invisible \r.

Example 3 · Bug: splitting a Windows file on \n

HiddenCrBugDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class HiddenCrBugDemo {    public static void main(String[] args) throws IOException {        Path file = Path.of("marks.csv");        // This file was made on Windows: every line ends in \r\n        Files.writeString(file, "Asha,86\r\nRavi,90\r\nEND\r\n");
        String[] lines = Files.readString(file).split("\n");        System.out.println("Lines: " + lines.length);
        String marksText = lines[0].split(",")[1];        System.out.println("Marks text length: " + marksText.length());        try {            System.out.println("Marks: " + Integer.parseInt(marksText));        } catch (NumberFormatException e) {            System.out.println("NumberFormatException: the text is not only digits");        }        System.out.println("Last line equals END? " + lines[2].equals("END"));
        Files.delete(file);    }}
Output
Lines: 3
Marks text length: 3
NumberFormatException: the text is not only digits
Last line equals END? false

What this code does

  • split("\n") cuts after each \n but leaves the \r before it. "86" is really "86\r": 3 characters, and parseInt rejects it.
  • The same hidden \r makes equals("END") false. Printed on screen, "END\r" looks exactly like END, which is why this bug is so hard to see.

Example 4 · The fix: lines(), split("\\R") or strip()

HiddenCrFixDemo.javaJava
import java.util.List;
public class HiddenCrFixDemo {    public static void main(String[] args) {        String text = "Asha,86\r\nRavi,90\r\nEND\r\n";
        List<String> lines = text.lines().toList();        int total = 0;        for (String line : lines) {            if (line.equals("END")) {                break;            }            total += Integer.parseInt(line.split(",")[1]);        }        System.out.println("lines(): " + lines.size() + " lines, total " + total);
        String[] parts = text.split("\\R");        System.out.println("split on \\R: " + parts.length + " lines, last is END? " + parts[2].equals("END"));
        System.out.println("strip(): " + Integer.parseInt("86\r".strip()));    }}
Output
lines(): 3 lines, total 176
split on \R: 3 lines, last is END? true
strip(): 86

What this code does

  • String.lines() (Java 11) splits on \r\n, \n and \r and removes them. Now equals("END") works and the loop stops at the right line.
  • \R in a regular expression means "any line break", so split("\\R") is the safe split. strip() removes whitespace at both ends, \r included, when you only have one line to clean.

The line still looks right when printed. But Integer.parseInt("86\r") throws NumberFormatException, "END\r".equals("END") is false, and lookups in a map by that text find nothing.

Find the bug

Find the line-ending bug

The file may come from Windows or from a Mac. Tap the line that breaks on one of them.

Read the marks of a file saved on Windows.

Round 1 of 3
If a String that looks right fails equals, print its length(). One extra character usually means a hidden \r.

Which methods handle both endings

The line-reading methods all treat \r\n, \n and a lone \r as one line break and remove it: Files.readAllLines, Files.lines, BufferedReader.readLine, String.lines() and Scanner.nextLine. In a regular expression, \R means "any line break", so split("\\R") is safe too.

Example 5 · Which methods handle both endings?

EndingsTableDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Scanner;
public class EndingsTableDemo {    static String check(List<String> lines) {        boolean hiddenCr = lines.stream().anyMatch(line -> line.contains("\r"));        return lines.size() + " lines" + (hiddenCr ? ", hidden \\r left" : ", clean");    }
    public static void main(String[] args) throws IOException {        String mixed = "Pen\r\nBook\nBag\r\nBox\n";        Path file = Path.of("mixed.txt");        Files.writeString(file, mixed);
        List<String> scanned = new ArrayList<>();        try (Scanner sc = new Scanner(mixed)) {            while (sc.hasNextLine()) {                scanned.add(sc.nextLine());            }        }
        System.out.println("Files.readAllLines : " + check(Files.readAllLines(file)));        System.out.println("String.lines()     : " + check(mixed.lines().toList()));        System.out.println("split on \\R        : " + check(Arrays.asList(mixed.split("\\R"))));        System.out.println("Scanner.nextLine   : " + check(scanned));        System.out.println("split on \\n        : " + check(Arrays.asList(mixed.split("\n"))));
        Files.delete(file);    }}
Output
Files.readAllLines : 4 lines, clean
String.lines()     : 4 lines, clean
split on \R        : 4 lines, clean
Scanner.nextLine   : 4 lines, clean
split on \n        : 4 lines, hidden \r left

What this code does

  • The text mixes both endings, as happens when two people edit one file on different computers. Every line-reading method copes; only the hand-made split("\n") leaves \r behind.
  • BufferedReader.readLine and Files.lines, which come later in this module, also handle both endings. The danger is only in code that splits or searches for \n by hand.

The risky code is your own: split("\n"), indexOf('\n') or counting \n characters. Use the line methods and the ending stops mattering.

Safe: readAllLines, Files.lines, readLine, lines(), nextLine and split("\\R").

Next step

Check your understanding

12 quick questions