串行化一个类,并存入文件中

 

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();
            }


 

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值