java 中的序列化和反序列化
import java.io.*;
/**
* stundent 类 实现serializable 接口 这样才能将这个类 的对象序列化
*
*/
public class Student implements Serializable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(String name) {
this.name = name;
}
}
class test {
public static void main(String[] args) {
Student sSave = new Student("LUO Hao");
save(sSave); // 将s持久保存
//Student sGet = (Student)getObj();
//String name = sGet.getName(); //反序列化 取出对象
}
/**
* 将一个对象序列化持久存储
* @param obj
*/
public static void save(Object obj) {
ObjectOutputStream os = null;
try {
FileOutputStream fo = new FileOutputStream("C:/bin.bin");
os = new ObjectOutputStream(fo);
os.writeObject(obj);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 反序列化
* @return 反序列化取出的object对象
*/
public static Object getObj() {
Object obj = null;
FileInputStream fi = null;
ObjectInputStream oi = null;
try {
fi = new FileInputStream("c:/bin.bin");
oi = new ObjectInputStream(fi);
obj = oi.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
fi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return obj;
}
}
C# 中的序列化和反序列化
序列化(其中obj 是任意一个对象)
FileStream fs = null;
BinaryFormatter bf = null;
try
{
fs = new FileStream(@"c:\bin.bat", FileMode.Create);
bf = new BinaryFormatter();
bf.Serialize(fs,obj);
}
catch (Exception ex)
{
throw ex;
}
finally {
fs.Close();
}
反序列化
FileStream fs = null;
BinaryFormatter bf = null;
try
{
fs = new FileStream(@"c:\bin.bat", FileMode.Create);
bf = new BinaryFormatter();
object obj = (object)bf.Deserialize(fs);
}
catch (Exception ex)
{
throw ex;
}
finally {
fs.Close();
}