[英]Which to use? new InputStreamReader with Socket.getInputStream or System.in
[英]BufferedReader with new InputStreamReader(System.in) throws an exception Temporarily unavailable resource
在我的獨立應用程序中,我必須從不同類的控制台讀取用戶輸入。 我在Installer class中創建了一個static class成員變量
public static final BufferedReader buffReader = new BufferedReader(new InputStreamReader(System.in));
但是 Installer.buffReader.readLine(); 拋出 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());
}
}
我該如何調試或防止它?
我認為是因為您在這里調用相同的方法:
if (userChoice != null && userChoice.equalsIgnoreCase("y")) {
startApplication();
}
所以第二次調用該方法會拋出異常,因為 bufferedReader 仍處於打開狀態。
在使用 buffReader.close() 之前嘗試關閉 bufferedReader。 或者不要將 static 用於 BufferedReader,因為如果應用程序的其他部分正在使用它,您也會遇到異常。
編輯:
我在谷歌上搜索了一下,可能是因為您的操作系統出於任何原因阻止了輸入。 我試過你的代碼,對我來說並沒有失敗。 檢查這里是一個類似的情況: 鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.