Video in progress
When you read a text file created on Windows on a Linux server, an invisible `\r` is left at the end of the lines. Where does it come from, and how do you handle it?
Windows marks the end of a line with \r\n, Linux with \n. split("\n") or manual parsing leaves the \r, while BufferedReader.readLine() recognizes all three variants correctly. When writing, you have to choose the format deliberately.
📖 Answer
The symptom usually looks strange: the last column in a CSV doesn't match "ACTIVE".equals(status), yet in the log both look like "ACTIVE". The cause is an invisible \r (code 13) at the end of the value.
String text = Files.readString(p);
String[] rows = text.split("\n"); // a \r is left at the end of every row
List<String> ok = text.lines().toList(); // Java 11+: recognizes \n, \r\n and \r
BufferedReader.readLine(), Files.lines, Files.readAllLines and String.lines() accept all three line endings and strip them. The problem only appears when you split the text yourself: split("\n"), setting the Scanner delimiter to \n, or parsing by bytes.
When writing:
System.lineSeparator()and%ninprintfgive the current OS's separator. The file will differ depending on which machine created it;BufferedWriter.newLine()also writes the OS separator;- if the file format is strict (a partner requires
\r\n, or a CSV per RFC 4180), write the separator by hand:w.write("\r\n").
To check: if cat -A file.csv shows ^M$ at the end of the line, it is the Windows format. If you don't control eol in Git with .gitattributes, even test fixture files end up different on different machines, and the test fails only on CI.
Sign up to mark studied questions and save your progress.