扫描仪 +系统处于停止状态
我正在使用 Scanner + System.in 读取文件。我在 Linux 中的命令如下所示:
cat -A test.txt | java -jar test.jar
我正在读取如下输入:
Scanner input = new Scanner(System.in);
while (input.hasNextLine())
{
String log_line = input.nextLine();
}
问题是.. 当到达文件末尾时如何停止读取?
I'm reading a file with Scanner + System.in. My command in Linux looks like:
cat -A test.txt | java -jar test.jar
I'm reading input like:
Scanner input = new Scanner(System.in);
while (input.hasNextLine())
{
String log_line = input.nextLine();
}
The question is.. How I can stop reading when the end of file is reached?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是 System.in 永远不会“结束”,即 EOF 永远不会发送到流,因此最后一行之后的 hasNextLine() 会阻塞等待更多数据。
解决方案是将文件名传递给您的应用,然后打开 FileInputStream(filePath) 并在 Scanner 构造函数中使用它。
The problem is that
System.in
never "ends", i.e. EOF is never sent to the stream, sohasNextLine()
after the last line is blocking waiting for more data.The solution is to pass the file name to your app, than you open
FileInputStream(filePath)
and use it in Scanner constructor.看来问题是 -A 选项,而不是你的java代码(它在普通文件上正常工作):
也许 test.txt 包含一些扫描仪无法处理的不可打印字符...
It seems that problem is -A option, not Your java code (it works correctly on plain files):
Maybe test.txt contains some non-printable chars that Scanner can't handle...