我有一个文件,其内容为“嗨,汤姆!\n”
。也就是说,文件的最后有一个换行符。
当此代码在该文件上运行时:
File file = new File(path.toString());
String content = new Scanner(file).useDelimiter("\\Z").next();
内容
中不存在尾随的\n
。如何保留 \n
?
最佳答案
Scanner.useDelimiter()
将其参数解释为 Pattern
(正则表达式)。并引用 Pattern
的 API 文档:
Summary of regular-expression constructs
Boundary matchers
\Z
– The end of the input but for the final terminator, if any\z
– The end of the input
因此,为了读取到文件末尾而不忽略最后一行终止符,请将 useDelimiter()
的参数从 "\\Z"
更改为“\\z”
。
关于java - 如何使 Scanner.next() 保留最后一个 "\n"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55624972/