序列化是其中对象可以表示为字节序列,包括该对象的数据的信息以及关于该对象的类型和类型存储在对象数据的机制。
的ArrayList已经实现了系列化,所以,在你的榜样,你可以写这样的事情:
ArrayList<String> al=new ArrayList<String>();
al.add("Jean");
al.add("Pierre");
al.add("John");
try{
FileOutputStream fos= new FileOutputStream("myfile.txt");
ObjectOutputStream oos= new ObjectOutputStream(fos);
oos.writeObject(al);
oos.close();
fos.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
在这里,我们将列表保存人在文件myfile.txt。
读取该文件,让你的ArrayList的时候,你会使用ObjectInputStream的:
FileInputStream fis = new FileInputStream("myfile.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<String> list = (ArrayList<String>) ois.readObject();
ois.close();
对于小的应用程序,例如HSQL,H2或Derby(JabaDB)嵌入式数据库也可以是一个不错的选择他们不需要设置专用的服务器应用程序。 –