Assignment: Create a program to practice reading in from a file, search for a particular word when the user inputs a word to search for and a file via command line args. Print out the entire line each time it is found.
Progress:
It compiles, and runs.... kinda.
Problem: I get a null pointer exception on line the line where I end the check for the word im searching for.
public class FindString{
public static void main(String args[]) throws FileNotFoundException,
IOException{
if(args.length != 2){
System.err.println("Usage: java FindString search-string "
+ "file-name");
}
String searchString = args[0]; //word to search for
String fileName = args[1]; // filename
FileReader fred = null;
try{
fred = new FileReader(fileName);
}
catch(FileNotFoundException fnf){
System.err.println("FileNotFoundException occurred: " +
fnf.getMessage());
}
try{
BufferedReader bread = new BufferedReader(fred);
int index;
String currentLine = "";
while(currentLine != null){ //read line by line while searching
currentLine = bread.readLine();
index = currentLine.indexOf(searchString); //NULLPOINTEREXCEPTION
if(index > 0){ // positive index if found
System.out.println(currentLine);
}
}
bread.close();
}
catch(IOException ioe){
System.err.println("IOException occurred: " + ioe.getMessage());
}
}
}
Why do i get the null pointer exception and how can I get rid of it???