【问题标题】:Inquiry about InputStream "System.in"查询 InputStream "System.in"
【发布时间】:2013-08-06 14:23:36
【问题描述】:

我想实现以下目标:

BufferedInputStream is = new BufferedInputStream(System.in);
        int c = 0;
        while((c=is.read())!=-1)
        Files.copy(is, path3, StandardCopyOption.REPLACE_EXISTING);

然而,它永远卡在等待 System.in 中。 有什么解决方法吗?

提前致谢。

【问题讨论】:

  • 它不能在构造函数处阻塞。你的意思是is.read()
  • 阻止尝试从控制台读取..您输入任何输入了吗?
  • 您是否在控制台按return?在此之前,System.in 看不到任何输入。
  • 如果您想在每次按键时做出反应,System.in 不适合您。您需要 AWT 事件。
  • 您是在控制台输入 ctrl/z 还是 ctrl/d(取决于系统)来提供 EOS?您的代码在得到一个之前不会终止。但是,您的代码无论如何都没有意义。您正在从 System.in 中读取一个字符,将其丢弃,然后复制整个流,然后重复直到读取的字符为 -1。这里的实际目标是什么?

标签: java io nio bufferedinputstream


【解决方案1】:

如果您尝试在换行或回车或流结束时停止阅读,您可以尝试-

do {

    try {

        c = is.read();

        // Do something

    } catch (IOException e) {

        e.printStackTrace();

    }

} while ((c != -1) & (c != '\n') & (c != '\r'));

【讨论】:

    猜你喜欢
    • 2021-07-23
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    相关资源
    最近更新 更多