I encounter a java.lang.NullPointerException error when running my Java program, and after reading up on it I think I understand what the error means, but I’m still not sure how to fix it.
import java.util.ArrayList;
import java.io.FileInputStream;
import java.io.DataInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintStream;
public class readFile {
public static ArrayList<String> pullFirst(String fileName) throws IOException{
String filen = "C:\\Users\\Steven\\Desktop\\Tests\\wunderground\\outputTweetsWeather.txt";
ArrayList<String> arl = new ArrayList<String>(); // java 6 ArrayList
FileInputStream fs = new FileInputStream(filen); // this is how you access a file in java
DataInputStream din = new DataInputStream(fs);
BufferedReader bin = new BufferedReader(new InputStreamReader(din));
String line;
while(!(line = bin.readLine()).startsWith("String index out of range")){ // read each line in the file while they exist
arl.add(line); // add them to the array list
}
return arl; // return the array list
}
public static void main(String[] args, int j) {
// this is just demo code to prove it works so you can check the output.
try{
ArrayList<String> rVal = pullFirst("testFile.txt");
for(String a : rVal){
//System.out.println(a + "\n"); // insert write to file code here
if(a.startsWith("+t")){
// System.out.println(a);
}
}
int i = 36;
PrintStream out5 = new PrintStream(new FileOutputStream("forpopUp1.txt", true));
System.setOut(out5);
System.out.println(rVal.get(2 + j*i)); // Display Value
}catch(Exception e){
System.out.print("Problem in readFile" + e);
}
}
}
Now I’m not sure if it’s to do with the fact that my main line is
public static void main(String[] args, int j) {
But, as far as I’m aware I have to have it this way, as this class is executed after an if condition from another class is ran, using the line
readFile.main(args, counterForreadFile);
This is the result of the StackTrace:
java.lang.NullPointerException
at readFile.pullFirst(readFile.java:22)
at readFile.main(readFile.java:33)
Any help would be appreciated!
I believe the error is when the file you read was exhausted:
While reading the file:
When the file is exhausted the
BufferedReaderwill returnnull.When you do
(line=bin.readLine()).startsWith(..)you actually try to invokestartsWith()onnullin this cases – and thus the error.To solve this, you should iterate as:
This provide you
nullsafety when the reader is exhausted.While it is definetly an issue – I cannot be sure it is the exact problem you are encountering until you provide a full stack trace.
P.S. As I already said in comments – getting the stack trace (which provides more information on the issue) you can add to your
catchblock, so it will be something like that:An alternative is to declare
main()asthrows Exception, and remove thecatchblock (andtryblock as well).