打印未找到文件的NullPointerException

时间:2013-03-29 12:17:19

标签: java file

如果找不到文件,如何打印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);
    } 
}

1 个答案:

答案 0 :(得分:1)

try {

...

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

}

它会打印所有例外情况,包括RunTimeException

NullPointerException