简体   繁体   English

BufferedReader with new InputStreamReader(System.in) 抛出异常资源暂时不可用

[英]BufferedReader with new InputStreamReader(System.in) throws an exception Temporarily unavailable resource

In my standalone application I have to read the user input from console in different classes.在我的独立应用程序中,我必须从不同类的控制台读取用户输入。 I created a static class member variable in Installer class我在Installer class中创建了一个static class成员变量

public static final BufferedReader buffReader = new BufferedReader(new InputStreamReader(System.in));

but Installer.buffReader.readLine();但是 Installer.buffReader.readLine(); throws an IO exception - "Temporarily unavailable resource" sometime抛出 IO 异常 - 有时“资源暂时不可用”

public static void startApplication() {
        System.out.println("Would you like to start the application? [y/n]");
        String userChoice = null;
        try {
            userChoice = Installer.buffReader.readLine();
            if (userChoice != null && userChoice.equalsIgnoreCase("y")) {
                start();
            }
        } catch (IOException ex) {
            LOGGER.error("Exception occured in startApplication() :{}", ex.getMessage());
        }
    }

How can I debug or prevent it?我该如何调试或防止它?

I think is because you are calling here to the same method:我认为是因为您在这里调用相同的方法:

if (userChoice != null && userChoice.equalsIgnoreCase("y")) {
            startApplication();
        }

so the second time you call the method is throwing you the exception because the bufferedReader is still opened.所以第二次调用该方法会抛出异常,因为 bufferedReader 仍处于打开状态。

Try to close the bufferedReader before with buffReader.close().在使用 buffReader.close() 之前尝试关闭 bufferedReader。 Or don't use the static for BufferedReader because if other part of the app is using it, you will have a exception as well.或者不要将 static 用于 BufferedReader,因为如果应用程序的其他部分正在使用它,您也会遇到异常。

EDIT:编辑:

I was searching a little bit in google and can be because your operative system that is blocking the input for any reason.我在谷歌上搜索了一下,可能是因为您的操作系统出于任何原因阻止了输入。 I tried your code and for me is not failing.我试过你的代码,对我来说并没有失败。 Check here is a similar case: Link检查这里是一个类似的情况: 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM