反序列化ArrayList



我正在尝试添加序列化和反序列化到我的应用程序。我已经添加了序列化,使其成为一个textfileThis问题涉及数组列表。我正在浏览这个页面:http://www.vogella.com/articles/JavaSerialization/article.html,当我看到这个代码:

FileInputStream fis = null;
    ObjectInputStream in = null;
    try {
      fis = new FileInputStream(filename);
      in = new ObjectInputStream(fis);
      p = (Person) in.readObject();
      out.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    System.out.println(p);
  }

我对这行很困惑:

p = (Person) in.readObject();

当创建数组列表时,我如何使这一行成为数组列表呢?

List<String> List = new ArrayList<String>();

提前感谢您的帮助!

我直接从您提供链接的网站中获取代码,并将其修改为ArrayList。你提到"当创建数组列表没有那么简单时,我如何使这一行成为数组列表",我说创建数组列表就像那样简单。

public static void main(String[] args) {
    String filename = "c:\time.ser";
    ArrayList<String> p = new ArrayList<String>();
    p.add("String1");
    p.add("String2");
    // Save the object to file
    FileOutputStream fos = null;
    ObjectOutputStream out = null;
    try {
        fos = new FileOutputStream(filename);
        out = new ObjectOutputStream(fos);
        out.writeObject(p);
        out.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    // Read the object from file
    // Save the object to file
    FileInputStream fis = null;
    ObjectInputStream in = null;
    try {
        fis = new FileInputStream(filename);
        in = new ObjectInputStream(fis);
        p = (ArrayList<String>) in.readObject();
        out.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    System.out.println(p);
}

打印出[String1, String2]

您是否在文件中编写了一个完整的ArrayList作为对象?或者你是否在文件的循环中写入了数组列表中的Persons对象?

最新更新