将可序列化的自定义对象读入文件android

时间:2016-11-16 18:18:30

标签: java android serialization

我正在尝试记录并将我的列表重新列入文件。在重新启动我的应用程序之前,它工作得很好。我正在使用模拟器(我在Android下没有真正的手机)

这是我将我的课程录制到文件中的功能:

public boolean writeRecordsToFile(String path, DummyContent object){
    FileOutputStream fos;
    ObjectOutputStream oos = null;
    try {
        fos = fileContext.openFileOutput(path, Context.MODE_PRIVATE);
        oos = new ObjectOutputStream(fos);
        oos.writeObject(object);
        oos.close();
        Log.d("fileManager", "Records write successfully");
        return true;
    } catch (Exception e) {
        Log.e("fileManager", "Cant save records : " + e.getMessage());
        return false;
    }
    finally {
        if (oos != null)
            try {
                oos.close();
            } catch (Exception e) {
                Log.e("fileManager", "Error while closing stream "+e.getMessage());
            }
    }
}

这是我的阅读功能:

public boolean readRecordsFromFile(String path){
    FileInputStream fin;
    ObjectInputStream ois=null;
    try {
        fin = fileContext.openFileInput(path);
        ois = new ObjectInputStream(fin);
        DummyContent records = (DummyContent) ois.readObject();
        records.addItem("test", "test", "test");
        ois.close();
        Log.d("fileManager", "Records read successfully :\n" + records.toString());
        Log.d("fileManager", "nbArticle found : " + String.valueOf(records.ITEMS.size()));
        Log.d("fileManager", "article 0 title :\n" + records.ITEMS.get(0).content);
        Log.d("fileManager", "article 10 title :\n" + records.ITEMS.get(10).content);
        return true;
    } catch (Exception e) {
        Log.e("fileManager", "Cant read saved records : "+e.getMessage());
        return false;
    }
    finally {
        if (ois != null)
            try {
                ois.close();
            } catch (Exception e) {
                Log.e("fileManager", "Error in closing stream while reading records : "+e.getMessage());
            }
    }
}

这是我的班级:

public class DummyContent implements Serializable {

/**
 * An array of sample (dummy) items.
 */
public static List<DummyItem> ITEMS = new ArrayList<DummyItem>();

/**
 * A map of sample (dummy) items, by ID.
 */
public static Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>();

public void addItem(String first, String second, String third) {
    DummyItem dummyItem = new DummyItem(first, second, third, android.R.drawable.ic_input_add);
    ITEMS.add(dummyItem);
    ITEM_MAP.put(dummyItem.id, dummyItem);
}

public void deleteAll() {
    ITEMS = new ArrayList<DummyItem>();
    ITEM_MAP = new HashMap<String, DummyItem>();
}

public void changeURL(Long index, String newURL) {
    ITEMS.get(index.intValue()).url = newURL;
}

public void changeContent(Long index, String newContent) {
    ITEMS.get(index.intValue()).contenu = newContent;
}

/**
 * A dummy item representing a piece of content.
 */
public static class DummyItem {
    public final String id;
    public final String content;
    public final String details;
    public final int imageResource;
    public String url;
    public String contenu;

    public DummyItem(String id, String content, String details, int imageResource) {
        this.id = id;
        this.content = content;
        this.details = details;
        this.imageResource = imageResource;
        this.url = "";
        this.contenu = "";
    }

    @Override
    public String toString() {
        return content;
    }
}

}

最后,我在我的MainActivity的onCreate(午餐应用程序的第一个活动)上阅读了我的文件:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    fileManager = new FileManager(this.getApplicationContext());
    Log.d("Main", String.valueOf(fileManager.fileExist("Article.art")));
    fileManager.readRecordsFromFile("Article.art"); /* Bug here : size of my array is empty but file's size is the same */
}

这是我的控制台返回:

  

D / fileManager:size = 102

     

D / fileManager:记录读取成功:   D / fileManager:nbArticle found:1(因为我在读取时添加了一个项目   功能)E / fileManager:无法读取保存的记录:索引:10,大小:1

我知道这是有效的,因为当我在写作后直接写作和阅读时,我得到了所有的项目,我可以阅读几次,我仍然得到所有项目(这个错误semms仅在我重新启动我的应用程序时出现)

也许我可以得到帮助?

谢谢!

1 个答案:

答案 0 :(得分:2)

原因很简单:您已将某些字段声明为 static ,标准序列化未涵盖这些字段:因此,这些字段的内容从未写入或从文件中读取。这就是为什么他们消失了#34; JVM重启后。

您要序列化/反序列化的任何字段,必须将其声明为实例成员(非静态)。

请参阅Serializable上的文档。