Kaleab
Kaleab

Reputation: 367

NullPointerException in my code

I wrote the following code, which opens a .txt file and writes its content to the console, but it shows me a NullPointerException, could you help me on debugging this?

box = new JFileChooser();

returnVal = box.showOpenDialog(null);
if (returnVal == box.APPROVE_OPTION) {
    File file = box.getSelectedFile();
}
try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    while (br.readLine() == null) {
        System.out.println(br.readLine());
    }
} catch (Exception e1) {
    e1.printStackTrace();
}

Upvotes: 0

Views: 54

Answers (2)

Yazan
Yazan

Reputation: 6082

i think this code have more than 1 mistake find changes 1-5 CHANGE 1 CHANGE 2 CHANGE 3 CHANGE 4 CHANGE 5

box = new JFileChooser();
File selectedFile = null; // CHANGE 1

returnVal = box.showOpenDialog(null);
if (returnVal == box.APPROVE_OPTION) {
    selectedFile = box.getSelectedFile(); // CHANGE 2
}
try {
    BufferedReader br = new BufferedReader(new FileReader(selectedFile ));//CHANGE 5
    String line = "";
    while ((line=br.readLine()) != null) {//CHANGE 3
        System.out.println(line);//CHANGE 4
    }

    br.close();//@Tom comment:
} catch (Exception e1) {
    e1.printStackTrace();
}

Upvotes: 2

Eran
Eran

Reputation: 393771

The file variable that you initialize only exists inside the scope of the if statement. You must be using a different file variable in the try block, which is probably not initialized (if you don't have another file variable declared in code you didn't include in the question, your code can't pass compilation).

Change

        if (returnVal == box.APPROVE_OPTION){
            File file = box.getSelectedFile();
        }

to

        if (returnVal == box.APPROVE_OPTION){
            file = box.getSelectedFile();
        }

Upvotes: 2

Related Questions