2013-06-18 78 views
0

我想从使用BufferedReader的输入中读取一个。它第一次运作,但第二次运行我得到一个异常。从System.in BufferedReader输入尝试抛出异常

[email protected]:~/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 

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

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; 
    } 

这真的好像都是关于commandLine()不工作的,所以我刚才包含了这个和main。

+0

在哪里定义了exit? –

+1

请发布一个可编辑的程序。 –

+0

@RohitJain它的Java 7 – sanbhat

回答

7

是的,你在这里关闭流:

try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) 

试图与 - 资源语句将关闭BufferedReader在块的结束,这将关闭InputStreamReader,这将关闭System.in

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

// Deliberately not closing System.in! 
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
try { 
    ... 
} 

它仍然是可能的,这将不完全的行为,只要你想,虽然,作为BufferedReader可能消耗(和缓冲区)更多数据。你最好创建BufferedReader一次(在调用代码中)并将它传递给方法。

哦,我建议你摆脱这样的:

String str = new String(); 

没有必要为它在所有。这会更好:

String str = ""; 

但即使如此,这是一个毫无意义的任务。同样,您不需要从readLine()返回的字符串中创建一个新的字符串。只需使用:

return br.readLine().trim(); 

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