The problem is that Files.lines() is implemented on top of BufferedReader.readLine() , which reads the line to the line terminator and discards it. Then, when you write lines with something like Files.write() , this gives a system line terminator after each line, which may differ from the line that was read.
If you really want to keep line terminators exactly as they are, even if they are a mixture of different line terminators, you can use regular expression and Scanner to do this.
First, define a pattern that matches a string containing valid string delimiters or EOF:
Pattern pat = Pattern.compile(".*\\R|.+\\z");
\\R is a special line separator that matches the usual line terminators and several Unicode line terminators that I have never heard of. :-) You can use something like (\\r\\n|\\r|\\n) if you want only regular CRLF , CR or LF .
You must include .+\\z to match the potential last "line" in a file that does not have a line terminator. Make sure that the regular expression always matches at least one character, so that no match will be found when the scanner reaches the end of the file.
Then read the lines using Scanner until you return null :
try (Scanner in = new Scanner(Paths.get(INFILE), "UTF-8")) { String line; while ((line = in.findWithinHorizon(pat, 0)) != null) {
source share