我有一个我要序列化的数组列表请告诉我如何能够这样做..
ArrayList list=new ArrayList();
list.add("Ram");
list.add("Sachin");
list.add("Dinesh");
list.add(1,"Ravi");
list.add("Dinesh");
list.add("Anupam");
System.out.println("There are "+list.size()+" elements in the list.");
System.out.println("Content of list are : ");
Iterator itr=list.iterator();
while(itr.hasNext())
System.out.println(itr.next());
}
}
我想使用序列化机制,以便将其保存在文件
中答案 0 :(得分:1)
很简单。 ArrayList
和String
(存储在列表中)都实现了Serializable
接口,因此您可以使用标准java机制进行序列化:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myfile"));
oos.writeObject(list);
............
oos.fluch();
oos.close();
在此示例中,我使用ObjectOutputStream包装FileOutputStream,但显然您可以使用任何其他有效内容流。
答案 1 :(得分:0)
您必须创建自己的方法来序列化和反序列化对象。以下是做到这一点的有用方法。
public static Object deserializeBytes(byte[] bytes) throws IOException, ClassNotFoundException
{
ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bytesIn);
Object obj = ois.readObject();
ois.close();
return obj;
}
public static byte[] serializeObject(Object obj) throws IOException
{
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bytesOut);
oos.writeObject(obj);
oos.flush();
byte[] bytes = bytesOut.toByteArray();
bytesOut.close();
oos.close();
return bytes;
}