0

NullPointerException如果找不到文件,如何打印?我想显示一条消息,JOptionPane但它没有用。

我尝试了以下方法:

public void readTextFile()  {
    FileInputStream fs = null;

    try {
        URL file2 = getClass().getResource("/ReadWriteFile/Student.txt");
        String file_path=file2.getPath();
        file_path=file_path.replaceFirst("/","");
        File file = new File(file_path);
        fs = new FileInputStream(file);
        BufferedReader reader = new BufferedReader(new InputStreamReader(fs));

        try {
            String line = reader.readLine();

            while(line != null){    
                System.out.println("line=="+line);    
                line = reader.readLine();
            }   
        } 

        catch (IOException e) {
            e.printStackTrace();
        }   
    } 

    catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null,"The file you trying to reach is not found");
        Logger.getLogger(Read_WriteToFile.class.getName()).log(Level.SEVERE, null, ex);
    } 
}
4

1 回答 1

1
try {

...

} catch (Exception e) {
     e.printStackTrace();

}

它将打印所有异常,包括RunTimeExceptions likeNullPointerException

于 2013-03-29T12:27:21.663 回答