I am trying to make a program that saves a list of strings to a file and then reads them into an arraylist. Here is my current code.
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream("friends.txt"));
} catch (FileNotFoundException e) {
File f = new File("friends.txt");
try {
f.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String obj;
try {
while ((obj = (String)input.readObject()) != null) {
friendly.add(obj);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This returns a null pointer exception. I am not quite sure what is going wrong here.
Well, for one thing, if the file doesn’t exist, ‘input’ will be null.
I’m not quite sure what the rationale is for handling the case of the file not existing in the way that you do– why not just test for the existence via File.exists() and only perform the opening and reading if it exists?
Other than that, as another commentator has said, provide a stack trace for a start.