扫描仪 +系统处于停止状态

发布于 2024-10-05 23:15:59 字数 323 浏览 0 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鲸落 2024-10-12 23:15:59

问题是 System.in 永远不会“结束”,即 EOF 永远不会发送到流,因此最后一行之后的 hasNextLine() 会阻塞等待更多数据。

解决方案是将文件名传递给您的应用,然后打开 FileInputStream(filePath) 并在 Scanner 构造函数中使用它。

The problem is that System.in never "ends", i.e. EOF is never sent to the stream, so hasNextLine() 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.

深海不蓝 2024-10-12 23:15:59

看来问题是 -A 选项,而不是你的java代码(它在普通文件上正常工作):

$ echo -e "foo\nbar" | java -jar Test.jar 
foo
bar
$

也许 test.txt 包含一些扫描仪无法处理的不可打印字符...

It seems that problem is -A option, not Your java code (it works correctly on plain files):

$ echo -e "foo\nbar" | java -jar Test.jar 
foo
bar
$

Maybe test.txt contains some non-printable chars that Scanner can't handle...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文