保存对象的数组列表并从文件中读取它

Save arraylist of objects and reading it from file

我在 fragmentActivity 中有一个对象数组列表

private List<Movie> myMovies = null;

我可以选择添加、删除以及电影列表中的所有内容,但是一旦我关闭应用程序,所有内容都将丢失。如何将数组保存到文件中并从文件中检索数组?

我有:

public void writeArray() {
    File f = new File(getFilesDir()+"MyMovieArray.srl");
    try {
        FileOutputStream fos = new FileOutputStream(f);
        ObjectOutputStream objectwrite = new ObjectOutputStream(fos);
        objectwrite.writeObject(myMovies);
        fos.close();

        if (!f.exists()) {
            f.mkdirs();
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 public ArrayList<Movie> read(Context context) {

      ObjectInputStream input = null;
      ArrayList<Movie> ReturnClass = null;
      File f = new File(this.getFilesDir(),"MyMovieArray");
      try {

       input = new ObjectInputStream(new FileInputStream(f));
       ReturnClass = (ArrayList<Movie>) input.readObject();
       input.close();

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

但它不起作用。 getFilesDir() 总是指向空指针异常 这是正确的方法吗? 关于如何将数组保存到文件并从文件中检索数组的任何建议?

更新 1: 找到修复,只需要编写 File f = new File(getFilesDir(), "MyMovieArray.srl"); 出现新问题:我有 onCreate 的代码:

myMovies = read(this);
    if(myMovies==null){
        myMovies = new ArrayList<Movie>();
        populateMovieListWithExamples();
        writeArray();
    }

每次我启动应用程序时,它总是显示带有填充示例的列表...如果我在重新打开后添加或删除它,它总是相同的列表。建议?

更新 2 只需要电影 class 可以序列化。感谢大家的帮助。祝大家有个美好的一天

您正在保存到 MyMovieArray.srl,但正在从 MyMovieArray 读取。另请阅读 MyMovieArray.srl

File 对象应该像这样创建(写入和读取):

File f = new File(getFilesDir(), "MyMovieArray.srl");

使用File f = new File(getFilesDir(), "MyMovieArray.srl");

在 writeArray() 和 read() 方法中