从文件读取和写入

时间:2013-09-05 18:33:37

标签: java android file-io

我正在努力学习如何用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不为null,但是ArrayLists为null且int为0.我计算这些值并写入文件。然后我再次读取该文件(用于调试目的)并发现我计算的所有数据现在都消失了。同样,EconAppData不为null,但是arraylists为null且int为零。

问题:如何正确读取和编写包含文件对象的类?

提前谢谢。

1 个答案:

答案 0 :(得分:5)

您的变量都是瞬态的,这意味着它们不会被保存/加载。 摆脱所有变量的瞬态属性。

请参阅:

Why does Java have transient fields?