我正在尝试将序列化和反序列化添加到我的应用程序中。我已经添加了序列化,使其成为文本文件。这个问题涉及 ArrayList。我正在浏览这个页面: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();
创建 ArrayList 时如何使这一行成为 ArrayList 并不那么简单:
List<String> List = new ArrayList<String>();
感谢您提前提供的帮助!
最佳答案
我直接从您提供链接的网站获取代码,并将其修改为 ArrayList。你提到“创建ArrayList时如何使这一行成为ArrayList没那么简单”,我说创建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]
关于java - 反序列化ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17126981/