0
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();
            }

        }


    }

}

The above code throws an unexpected exception - NullPointerException in one of the try block on the following line: output.close();. Can anyone explain the reason for that? Any help would be appreciated. Thanks in advance.

Borislava
  • 49
  • 9

1 Answers1

0

The line

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

might throw before output is initialized. Hence output == null when attempting to execute output.close();. Maybe you meant something like this instead:

if (output != null)
     output.close();
jotik
  • 17,044
  • 13
  • 58
  • 123