-1

我在这部分需要帮助

        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 新手

4

1 回答 1

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");
} 
于 2014-05-22T02:45:45.380 回答