2

我目前正在开发一个android项目,当我写出我的对象时没有存储它们。

这是我编写它们的方式,其中 cont 是 Contact 类型的 ArrayList

if (contacts.size() > 0){
        File fout = new File(c.getCacheDir(), "contacts.acl");
        if (fout.exists()){
            try{
                ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fout, false)));
                for (Contact cont : contacts){
                    Log.d(MYACT, "Writing out: " + cont.getfName());
                    out.writeObject(cont);
                }
                out.flush();
                out.close();
            }catch (Exception e){e.printStackTrace();}
        }
    }

这就是我阅读它们的方式

private ArrayList<Contact> readContacts(){
    ArrayList<Contact> contactList = new ArrayList<Contact>();
    File file = new File(c.getCacheDir(), "contacts.acl"); //get contact file
    Log.d(MYACT, "Launch File exists: " + file.exists());
    if (file.exists()){ // if it exists then read in contacts while there are contacts left
        try{

            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
            Log.d(MYACT, "Reading from file. Available: " + in.available());
            while (in.available() > 0){
                Contact cont = (Contact)in.readObject();
                Log.d(MYACT, "Read in: " + cont.getfName());
                contactList.add(cont);
            }
            in.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    else // else creates the file
        try{
            file.createNewFile();
        }catch (IOException e){}

        return contactList;
}

起初我虽然是因为我错过了关闭流,但它们都关闭了。可能是什么问题呢?是否有任何其他解决方案来存储对象。最初我拥有它以便将每个联系人存储在同一个文件中,但后来我将其转移到存储联系人的 ArrayList 中。

谢谢你的帮助。

4

1 回答 1

1

您已写入ObjectOutputStream. 所以不需要检查 in.available() 替换 while 循环

while (in.available() > 0){
                Contact cont = (Contact)in.readObject();
                Log.d(MYACT, "Read in: " + cont.getfName());
                contactList.add(cont);
            }
            in.close();
        }catch (Exception e){
            e.printStackTrace();
        }

while (true){
                        Contact cont = (Contact)in.readObject();
                        contactList.add(cont);
                    }
                }
                catch(EOFException eof){}
                catch (Exception e){
                    e.printStackTrace();
                }
于 2013-11-08T07:00:15.077 回答