package Test;
import java.io.*;public class TestFile {
public static void main(String[] args)
{
FileReader input = null;
try 
{
   input = new FileReader("yrdy");
   int code;
   while((code=input.read())!=-1)System.out.print((char)code);
}
catch(FileNotFoundException ex){}
catch(IOException ex)
{
ex.printStackTrace();
}
finally
{
try{input.close();}
catch(IOException ex){}
}
}
}当input=new FileReader("yrdy");中的那个文件不存在的时候,为什么会报错?
Exception in thread "main" java.lang.NullPointerException
at Test.TestFile.main(TestFile.java:22)

解决方案 »

  1.   

    当文件不存在时
    try { 
       input = new FileReader("yrdy"); 
       int code; 
       while((code=input.read())!=-1)System.out.print((char)code); 
    }
    try 语句块执行无效,此时 input == null
    在 finally 语句块中调用 input.close(); 当然会出现空指针异常了.
    import java.io.*;public class thisT {
    public static void main(String[] args) {
    FileReader input = null;
    try {
    input = new FileReader("yrdy");
    int code;
    while ((code = input.read()) != -1)
    System.out.print((char) code);
    } catch (FileNotFoundException ex) {
    } catch (IOException ex) {
    ex.printStackTrace();
    } finally {
    try {
    input.close();
    } catch (IOException ex) {
    } catch (NullPointerException ex) {}
    }
    }
    }
      

  2.   

    try 
    {
       input = new FileReader("yrdy");
       int code;
       while((code=input.read())!=-1)System.out.print((char)code);
    }
    catch(FileNotFoundException ex){} 

    当文件不存在的时候,进入到这个catch中,不过你在这个catch中没有任何代码,程序继续执行finally里面的代码input.close();
    虽然这个下面的catch也没有任何代码,打印的异常并不是下面要捕获的IOException而是一个runtime异常java.lang.NullPointerException,runtime异常不用显示的捕获。