Reputation: 2050
I am struggling with how to read and write to a file in Java.
I have the following class which will be written to a file:
public class EconAppData implements Serializable {
private static final long serialVersionUID = 1432933606399916716L;
protected transient ArrayList<Favorite> favorites;
protected transient List<CatalogTitle> catalogLists;
protected transient int rangeMonthlySettings;
protected transient int rangeQuarterlySettings;
protected transient int rangeAnnualSettings;
EconAppData() {
favorites = new ArrayList<Favorite>();
catalogLists = new ArrayList<CatalogTitle>();
rangeMonthlySettings = 3;
rangeQuarterlySettings = 5;
rangeAnnualSettings = -1;
}
}
This is my read method:
protected Object readData(String filename) {
Object result;
FileInputStream fis;
ObjectInputStream ois;
try {
fis = openFileInput(filename);
ois = new ObjectInputStream(fis);
result = ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.err.println(filename + " not found");
return null;
} catch (StreamCorruptedException e) {
e.printStackTrace();
System.err.println(filename + " input stream corrupted");
return null;
} catch (IOException e) {
e.printStackTrace();
System.err.println("I/O error in reading " + filename);
return null;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
return result;
}
And the write method:
protected Object writeData(String filename, Object data) {
FileOutputStream fos;
ObjectOutputStream oos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(data);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.err.println(filename + " not found");
} catch (StreamCorruptedException e) {
e.printStackTrace();
System.err.println(filename + " output stream corrupted");
} catch (IOException e) {
e.printStackTrace();
System.err.println("I/O error in writing " + filename);
}
return null;
}
The issue: when I am debugging my code, it appears that I am read and writing to my file (so long as the file exists) without hitting any exceptions. I read my data and find that EconAppData is not null, however the ArrayLists are null and the ints are 0. I compute these values and write to the file. I then read the file again (for debugging purposes) and find that all of the data I computed is now gone. Again the EconAppData is not null, however the arraylists are null and the ints are zero.
The question: How do I correctly read and write a class that also contains objects to a file?
Thank you in advance.
Upvotes: 0
Views: 167
Reputation: 1706
Your variables are all transient which means they don't get saved/loaded. Get rid of the transient attributes from all your variables.
See:
Why does Java have transient fields?
Upvotes: 5