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.");
}
}