Why has this file I/O operation in Java caused NullPointerException

2020-02-15 java file nullpointerexception

I was writing code for a small tool that removes a user-given string from a file whose name is fed to the program from the command line. But when run, it throws a NullPointerException. I can't figure out why. Please help me solve this mystery. Thank you very much. This code is as follows.

/**
 * Remove certain lines from a text file.
 */

import java.util.*;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class LineCutter {
    public static void main(String[] args) {

        if (args.length < 1) {
            System.out.println("Usage: java LineCutter filename");
            System.exit(1);
        }
        System.out.println("Enter the line to be removed:");
        Scanner lineToRemove = new Scanner(System.in);
        lineToRemove.nextLine();
        FileReader fr = null;
        FileWriter fw = null;
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            fr = new FileReader(args[1]);
            br = new BufferedReader(fr);
            fw = new FileWriter(new File("output.txt"));
            bw = new BufferedWriter(fw);

            String line = br.readLine();
            while(line != null) {
                if (!line.equals(lineToRemove))
                    bw.write(line);
                line = br.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                br.close(); // NullPointerException
                fw.close();
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Operations finished.");
    }
}

Answers

If fr = new FileReader(args[1]) throws an exception then br will be null when you attempt to call br.close() and the NullPointerException will hide the actual problem. Your problem is most likely the use of 1 as the index causing an ArrayIndexOutOfBoundsException. You expect only one element in the args array, so you should be using args[0]. Remember, arrays are zero-based.

Also, you should be using a try-with-resources statement. It handles closing everything for you automatically in a null-safe manner. For example:

try (BufferedReader br = new BufferedReader(new FileReader(args[0]));
     BufferedWriter bw = new BufferedWriter(new FileWriter(new File("output.txt")))) {
  // I/O code...
} catch (IOException ex) {
  ex.printStackTrace();
}

Not sure what the following code is supposed to be doing:

System.out.println("Enter the line to be removed:");
Scanner lineToRemove = new Scanner(System.in);
lineToRemove.nextLine();

You don't do anything with result of lineToRemove.nextLine(). Though later you test if a String is equal to lineToRemove, which will always be false. Perhaps you mean:

String lineToRemove = new Scanner(System.in).nextLine();

Probably because fr = new FileReader(args[1]); is throwing an exception (probably because it can't find the file specified in args[1]), and so br continue to be null, and so you are invoking .close() in a null object.
I would also point out that here:

if (!line.equals(lineToRemove))
                bw.write(line);

you are invoking equals between a String and a Scanner

Related