簡體   English   中英

如何從單個文件保存和多個對象?

[英]How do I save and multiple objects from a single file?

我正在嘗試創建一個系統,用戶可以在其中選擇一組ID(聯盟ID)來從外部API檢索數據。 從Web服務檢索數據后,我希望將其存儲在本地以供以后使用。 現在,我的問題是我知道如何通過獲取整個文件(federations.dat)從ObjectInputStream加載對象。 我有辦法從“ federations.dat”加載“ WHERE id = N的對象”嗎? 還是我必須為每個對象創建單獨的文件?

這是我的加載方法:

public static Object load(Context ctx, String filename) throws FileNotFoundException 
{
    Object loadedObj = null;
    InputStream instream = null;

    instream = ctx.openFileInput(filename);

    try {
        ObjectInputStream ois = new ObjectInputStream(instream);
        loadedObj = ois.readObject();
        return loadedObj;

    } catch (StreamCorruptedException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

有什么建議嗎?

您可以像這樣使用它。

ArrayList<Object> arrayList = new ArrayList<Object>();

Object obj = null;

while ((obj = ois.readObject()) != null) {
    arrayList.add(obj);
}

您可以在您的方法上返回ArrayList。

return arrayList;

編輯:完整的代碼將是這樣。

public static ArrayList<Object> load(Context ctx, String filename) 
{
    InputStream fis = null;
    ObjectInputStream ois = null;

    ArrayList<Object> arrayList = new ArrayList<Object>();

    Object loadedObj = null;
    try {
        fis = ctx.openFileInput(filename);
        ois = new ObjectInputStream(fis);

        while ((loadedObj = ois.readObject()) != null) {
             arrayList.add(loadedObj);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (null != ois) ois.close();
        if (null != fis) fis.close();
    }

    return arrayList;
}

希望能幫助到你..

擴展到@Jan的代碼,解決了拋出異常時保持ois打開的問題以及一些小問題。

public static ArrayList<Object> load(Context ctx, String filename) throws FileNotFoundException {
    InputStream instream = ctx.openFileInput(filename);

    ArrayList<Object> objects = new ArrayList<Object>();

    try {
        ObjectInputStream ois = new ObjectInputStream(instream);
        try{
            Object loadedObj = null;
            while ((loadedObj = ois.readObject()) != null) {
                objects.add(loadedObj);
            }

            return objects;
        }finally{
            ois.close();
        }

    } catch (StreamCorruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM