Java GUI - 错误消息不断弹出

时间:2014-05-22 02:42:51

标签: java swing io file-search

我在这部分需要帮助

        try{    
                FileReader fr = new FileReader("C:\\test.txt");
                BufferedReader br = new BufferedReader(fr);        

              String text = txtKeyword.getText();  
              String line = null;
              boolean hasError = false;

            while ((line = br.readLine()) != null) {                                    

            if(line.contains(text)){
                String newline = "\n";
                jTextArea1.append(text + newline);
                hasError = false;
            }
            else{
                hasError = true;
            }

        }
            br.close();
            if (hasError) {
                   System.out.println("Text not found");
                } 
            }catch(IOException e){
            System.out.println("File not found");
        }   }

好的,我做了所说的但每次收到正确的关键字时我仍然会收到一条错误消息。反正有改变吗?我问题的任何解决方案?或者,如果不使用null,我还应该使用什么?请指导我......这里有Java新手

1 个答案:

答案 0 :(得分:2)

永远不要忽略异常

    FileReader fr = null;
    try {
        fr = new FileReader("C:\\test.txt");
    } catch(IOException e){

          // do something here - no point in continuing
    }

如果您只想要一条错误消息,那么

 boolean hasError = true;
 while ((line = br.readLine()) != null) {                                    

    if(line.contains(text)){

        String newline = "\n";
        jTextArea1.append(text + newline);
        hasError = false;
    }
}

if (hasError) {
   System.out.println("Text not found");
}