2013-05-05 20 views
0

所以我試圖重定向到System.in文本框。我已經看到了這個線程Redirect System.in to swing component,而且似乎擁有一切工作:Java重定向System.in - InputStream.read調用,但沒有「返回」

private class SystemIn extends InputStream { 

    @Override 
    public int read() { 
     int x = GUIConsole.this.read(); 
     System.out.println("Read called: returning " + x); 
     return x; 
    } 

} 

的讀取似乎是正確執行的:我有一個幫手

public static String readLine(String msg) { 
    String input = ""; 
    InputStreamReader converter = new InputStreamReader(System.in); 
    BufferedReader in = new BufferedReader(converter); 

    while (input.length() == 0) { 
     try { 
      print(msg); 
      input = in.readLine().trim(); 
     } catch (Exception ignore) { 
      // 
     } 
    } 
    return input; 
} 

我呼籲

String in3 = SimpleConsole.readLine("Enter text: "); 
System.out.println("You said: " + in3); 

因此打印"Read called: returning #"。當我打電話時,我得到正確的字符代碼,最後是-1。讀取方法阻塞,直到輸入準備就緒,如文檔指定。但是,我只收到"Read called..."消息,並且下一行("You said...「)從不執行(它仍然停留在閱讀狀態)。我不知道問題出在哪裏 - 如果你想看更多代碼(雖然我覺得"Read called..."的消息顯示它在做正確的事),只是讓我知道。

有別的我應該做的是能夠調用readLine,並從一個文本框輸入?我也試着重寫輸入流中的其他方法沒有運氣(再次,read方法正在執行)

回答

0

唉,像往常一樣,我發現在我發佈一個問題後很快回復(我也會每次都這樣說)。無論如何,如果其他人正在尋找:

當讀取/實現輸入流時,確保最後一次調用返回換行字符 \n'(後跟-1)。因爲如果您正在讀取,它將等待最後一個換行符。

因此,對於我來說,我追加文本字段加上一個換行符。現在它運行起來,程序完成閱讀並打印最終消息。

+0

看起來像SO是你的橡皮鴨調試器。 ( - :見:http://en.wikipedia.org/wiki/Rubber_duck_debugging – 2013-12-23 20:05:43

相關問題