来自System.in的BufferedReader输入尝试抛出异常

Joh*_*ate 1 java input bufferedreader inputstreamreader

我试图使用BufferedReader从输入中读取a.它第一次工作,但第二次运行我得到一个例外.

john@fekete:~/devel/java/pricecalc$ java frontend.CUI 
> gsdfgd
Invalid command!
> I/O Error getting string:  java.io.IOException: Stream closed
I/O Error: java.io.IOException: java.io.IOException: Stream closed
> I/O Error getting string:  java.io.IOException: Stream closed
I/O Error: java.io.IOException: java.io.IOException: Stream closed
> I/O Error getting string:  java.io.IOException: Stream closed
Run Code Online (Sandbox Code Playgroud)

它只是在循环中继续运行.我一定错过了什么.

public static void main(String args[]) {
            if (args.length == 0) {
                    while (!exit) {
                            try {
                                    exit = processLine(commandLine());
                            } catch (IOException e) {
                                    System.out.println("I/O Error: " + e);
                            }
                    }
                    System.out.println("Bye!");
            } else if (args.length == 1) {
                    String line = new String(args[0]);
                    processLine(line);
            } else {
                    String line = new String(args[0]);
                    for (String np : args) {
                            line = new String(line + " " + np); 
                    }
                    processLine(line);
            }
    }

    static private String commandLine() throws IOException {
            String str = new String();
            try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
                    System.out.print("> ");
                    str = new String(br.readLine());
                    str = str.trim();
            } catch (IOException e) {
                    System.out.println("I/O Error getting string: "+ str + " " + e);
                    throw new IOException(e);
            }

            return str;
    }
Run Code Online (Sandbox Code Playgroud)

它真的似乎都是关于commandLine()不工作所以我只是包括那个和主要.

Jon*_*eet 8

是的,你在这里关闭流:

try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in)))
Run Code Online (Sandbox Code Playgroud)

try-with-resources语句将关闭BufferedReader块的末尾,这将关闭InputStreamReader,将关闭System.in.

在这种情况下你不想这样做,所以只需使用:

// Deliberately not closing System.in!
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));   
try {
    ...
}
Run Code Online (Sandbox Code Playgroud)

尽管如此,它仍然可能不会像你想要的那样完全表现,因为它BufferedReader可能会消耗(和缓冲)更多的数据.你最好创建BufferedReader 一次(在调用代码中)并将其传递给方法.

哦,我建议你摆脱这个:

String str = new String();
Run Code Online (Sandbox Code Playgroud)

根本不需要它.这会更好:

String str = "";
Run Code Online (Sandbox Code Playgroud)

但即便如此,这也是毫无意义的任务.同样,您不需要从返回的String创建新的String readLine().只需使用:

return br.readLine().trim();
Run Code Online (Sandbox Code Playgroud)

......在try街区内.此外,strcatch块内进行记录没有意义,因为它将是空的 - IOException只有在读取行时才会抛出...