2012-11-17 23 views
0

如何閱讀和打印文本文件中的內容?閱讀文件中的文本

我可以在showInputDialog()中調用readFile()方法嗎? 例如:

String q = (String)JOptionPane.showInputDialog(frame, 
         "what is your name", 
         "Get Name Demo", 
         JOptionPane.PLAIN_MESSAGE, 
         null, 
         null, 
         readText()); 

private String readText()throws Exception{ 
    BufferedReader reader = null; 

     reader = new BufferedReader(new FileReader("data/name.txt")); 
      String name = reader.readLine(); 
      StringTokenizer st = new StringTokenizer(name, " "); 
      String NAME= st.nextElement().toString(); 

      if(reader!=null) 
      reader.close();    

     return NAME; 
    } 

錯誤: 未報告的異常java.lang.Exception的;必須捕獲或聲明拋出

回答

0

readText方法拋出一個checked異常,你需要控制。

可以使用try-catch塊,或在使用你的readText方法你的方法添加throws條款。

這樣做:

try{ 
String q = (String)JOptionPane.showInputDialog(frame, 
         "what is your name", 
         "Get Name Demo", 
         JOptionPane.PLAIN_MESSAGE, 
         null, 
         null, 
         readText()); 
}catch(Exception e){ 
//do the stuff that you want to do if there was some prblem reading your file 
} 

或者添加一個throws Exception子句圍住,上面代碼的String q = ....部件的製備方法。

一個你可能會喜歡做更多的事情是有一個try-catch塊你readText方法內部並存儲在一個字符串和catch塊從文件中讀取內容創建包含像Unable to read file一些消息的字符串,返回字符串從你的方法。

private String readText(){ 
// Note that I have removed that throws Exception from above 
BufferedReader reader = null; 
String myText=""; 
try{ 
     reader = new BufferedReader(new FileReader("data/name.txt")); 
     String name = reader.readLine(); 
     StringTokenizer st = new StringTokenizer(name, " "); 
     String NAME= st.nextElement().toString(); 
     myText = NAME;    
}catch(Exception e){ 
     myText = "Unable to read file";//or any message you want to convey 

}finally{ 
     if(reader != null){ 
      try{ 
      reader.close(); 
      }catch(Exception e){ 
      } 
     } 
} 
return myText; 

} 
+0

我試圖把try-catch塊中READFILE()方法和方法已被調用。 bu仍然無法正確輸出。當我嘗試分配像'String myText =「aaaaaa」'這樣的變量時,它打印出'aaaaaa'。 – aaaa

+0

你的意思是字符串'myText'沒有填充文件的內容嗎? – Abubakkar

0

你忘了處理在調用方法的異常,以便避免拋出這樣

private String readText(){ 


    BufferedReader reader = null; 
    String NAME =""; 

    try 
    { 

      reader = new BufferedReader(new FileReader("data/name.txt")); 
      String name = reader.readLine(); 
      StringTokenizer st = new StringTokenizer(name, " "); 
      NAME= st.nextElement().toString(); 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 
    finally 
    { 
     if(reader!=null) 
       reader.close(); 
    return NAME; 
    } 
} 
+0

謝謝。現在問題是在添加try-catch塊後,可以編譯按鈕不起作用 – aaaa

+0

ok打印stacktrace並顯示它說什麼。我認爲這是由於fileNotFoundException。 – sunleo

+0

現在檢查已編輯答案的檢查並顯示異常跟蹤。 – sunleo