序列化ArrayList中的Andr​​oid不工作序列化、工作、Andr、ArrayList

2023-09-08 09:08:33 作者:帅到失控

更新:后位的测试,我确定自己被心不是创建的文件,至少根据file.exists反正检查。任何想法?

UPDATE: After a bit of testing I've determined the file itself isnt being created, at least according to the file.exists check anyway. Any ideas?

你好,我想在我的应用程序退出序列化一个ArrayList和读回的续时。它似乎没有要创建该文件。

Hi I'm trying to serialize an arraylist when my app is exited and read it back when its resumed. It doesnt seem to be creating the file.

下面是我的code。

protected void onPause() {
    super.onPause();

    if(!myArrayList.isEmpty())
    {
        final String FILENAME = "myfile.bin";
        try{
            FileOutputStream fos;

            fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);

            //FileOutputStream fileStream = new FileOutputStream(FILENAME);
            ObjectOutputStream os = new ObjectOutputStream(fos);
            os.writeObject(myArrayList);
            os.flush();
            os.close();
        } catch (FileNotFoundException e) {
                e.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
    }
}

@SuppressWarnings("unchecked")
    @Override
    protected void onResume() {
        super.onResume();

    File file = new File("myfile.bin");
    if(file.exists()){
        final String FILENAME="myfile.bin";
        try{
            FileInputStream fileStream = new FileInputStream(FILENAME);
            ObjectInputStream os = new ObjectInputStream(fileStream);
            myArrayList = (ArrayList<MyObject>)os.readObject();
            os.close();
        } catch (FileNotFoundException e) {
                e.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
        }
    }




}

任何想法?我为MyObject类实现序列化。

Any ideas? My MyObject class implements serializable.

推荐答案

明白了通过更改的FileInputStream FILESTREAM =新的FileInputStream(文件名)到的FileInputStream FILESTREAM = openFileInput(文件名)。

 
精彩推荐
图片推荐