意外异常:java.lang.NullPointerException

时间:2016-05-16 08:09:08

标签: java nullpointerexception

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Example {

    public static void main(String[] args) {
        BufferedReader input = null;
        BufferedWriter output = null;
        try{
            int c;
            input = new BufferedReader(new FileReader("readfile.txt"));
            output = new BufferedWriter(new FileWriter("writefile.txt"));
            while ((c=input.read())!= -1) {
                output.write(c);
            }
        } catch (FileNotFoundException fnfe){
                System.err.println("The file was not found.");
                fnfe.getMessage();
        } catch (IOException ioe) {
            System.err.println("The file could not be read.");
            ioe.getMessage();
        }finally {
            try {
                output.close();
            } catch (IOException e) {
                System.err.println("The file was not opened.");
                e.printStackTrace();
            }
            try {
                input.close();
            } catch (IOException e) {
                System.err.println("The file couldn't be closed.");
                e.printStackTrace();
            }

        }


    }

}

以上代码在以下行的try块中抛出一个意外的异常 - NullPointerException: output.close();. 任何人都可以解释原因吗?任何帮助,将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:0)

该行

input = new BufferedReader(new FileReader("readfile.txt"));

可能会在output初始化之前抛出。因此在尝试执行output == nulloutput.close();。也许你的意思是这样的:

if (output != null)
     output.close();