问题是Files.lines()
是在之上实现的BufferedReader.readLine()
,它读取一行直到行终止符并将其丢弃。然后,当你用类似的东西写行时Files.write()
,这会在每行之后提供系统特定的行终止符,该终止符可能与读入的行终止符不同。
如果您确实想按原样保留行终止符,即使它们是不同行终止符的混合,您也可以使用正则表达式和Scanner
为了那个原因。
首先定义一个匹配包含有效行终止符或 EOF 的行的模式:
Pattern pat = Pattern.compile(".*\\R|.+\\z");
The \\R
是一个特殊的换行匹配器,它匹配通常的行终止符以及一些我从未听说过的 Unicode 行终止符。 :-) 你可以使用类似的东西(\\r\\n|\\r|\\n)
如果你只想要平常的CRLF, CR, or LF终结者。
你必须包括.+\\z
为了匹配文件中没有行终止符的潜在最后“行”。确保正则表达式始终匹配至少一个字符,以便扫描程序到达文件末尾时找不到匹配项。
然后,使用 a 读取行Scanner
直到它返回null
:
try (Scanner in = new Scanner(Paths.get(INFILE), "UTF-8")) {
String line;
while ((line = in.findWithinHorizon(pat, 0)) != null) {
// Process the line, then write the output using something like
// FileWriter.write(String) that doesn't add another line terminator.
}
}