如何将同一个Class的多个对象序列化为单个文件,并在c#
中反序列化为那些对象答案 0 :(得分:3)
尝试这样的事情:
using (FileStream output =
new FileStream("C:\\peoplearray.dat", FileMode.CreateNew))
{
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(output,
new Person[] {
new Person{Firstname="Alex"}
});
}
using (FileStream input =
new FileStream("C:\\peoplearray.dat", FileMode.Open))
{
BinaryFormatter bformatter = new BinaryFormatter();
var results = bformatter.Deserialize(input) as Person[];
foreach (Person p in results)
{
Console.WriteLine(p.Firstname);
}
}
只要有人[Serializable],这将有效
答案 1 :(得分:2)
序列化和反序列化这些对象的数组。
答案 2 :(得分:0)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class SerializeMe implements Serializable {
private static final long serialVersionUID = 1L;
private int data;
public SerializeMe (int data) {
this.data = data;
}
public int getData() {
return data;
}
}
public class UIDTester {
public static void main(String... strings) throws Exception {
File file = new File("out.ser");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
//Create the multiple Objects
SerializeMe serializeMe = new SerializeMe(1);
SerializeMe serializeMe1 = new SerializeMe(10);
SerializeMe serializeMe2 = new SerializeMe(100);
SerializeMe serializeMe3 = new SerializeMe(1000);
//Create an array and assign objects
Object[] obj=new Object[]{serializeMe,serializeMe1,serializeMe2,serializeMe3};
// Write object array to Stream Class
oos.writeObject(obj);
oos.close();
//Process of Deserializable
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
//create an array of Object class
Object[] obj1=(Object[]) ois.readObject();
//looping the array
for(int i=0;i<obj1.length;i++){
SerializeMe dto = (SerializeMe) obj1[i];
System.out.println("data : " + dto.getData());
}
ois.close();
}
}