我正在为如何在 Java 中读取和写入文件而苦苦挣扎。
我有以下将写入文件的类:
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;
}
}
这是我的阅读方法:
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;
}
和写方法:
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;
}
问题:当我调试我的代码时,似乎我正在读取和写入我的文件(只要文件存在)而没有遇到任何异常。我读取了我的数据,发现 EconAppData 不为空,但是 ArrayLists 为空且整数为 0。我计算这些值并写入文件。然后我再次读取该文件(出于调试目的),发现我计算的所有数据现在都消失了。同样,EconAppData 不为空,但数组列表为空且整数为零。
问题:如何正确读取和写入一个还包含文件对象的类?
先感谢您。