读取文件中的文字

时间:2012-11-17 10:17:25

标签: java user-interface

如何阅读和打印文本文件中的内容?

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

  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;必须被捕获或声明被抛出

2 个答案:

答案 0 :(得分:0)

您的readText方法会抛出您需要控制的已检查异常。

您可以使用try-catch块,或在方法中添加使用throws方法的readText子句。

这样做:

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;

}

答案 1 :(得分: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;
    }
}