序列化和反序列 properties

当对象在传输或存储的过程中,无法直接进行此操作,需要序列化。

在Java语言中,将对象序列化,存储到文件中,要实现这一过程,其类要实现序列化接口,我们拿学生类为例:

 

public class Student implements Serializable{
	private static final long serialVersionUID = 1L;//生成版本序列号
	private String name;
	private String ID;
	private String sex;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getID() {
		return ID;
	}
	public void setID(String iD) {
		ID = iD;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	@Override
	public String toString() {
		return " [name=" + name + ", ID=" + ID + ", sex=" + sex + "]";
	}
}

实现序列化实例:

 

 

public static void main(String[] args) throws IOException, IOException {
		Student student=new Student();
		student.setName("小明");
		student.setID("201405251");
		student.setSex("男");
		ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("aa.txt"));
		oos.writeObject(student);
		oos.close();
	}

实现反序列化,读取文件中的数据:

 

 

public static void main(String[] args) throws IOException, IOException, ClassNotFoundException {
		ObjectInputStream ois=new ObjectInputStream(new FileInputStream("aa.txt"));
		Student student=(Student) ois.readObject();
		System.out.println(student);
	}

properties在Java中大多是对配置文件的读写吧,通过键值对存取:

 

 

public static void main(String[] args) throws IOException, IOException {
		Properties properties=new Properties();
		properties.setProperty("name", "小明");
		properties.setProperty("sex", "男");
		properties.store(new FileOutputStream("bb.properties"),null);
	}

从文件中读取时:

 

 

public static void main(String[] args) throws IOException, IOException {
		Properties properties=new Properties();
		properties.load(new FileInputStream("bb.properties"));
		System.out.println("name  "+properties.getProperty("name"));
		System.out.println("sex   "+properties.getProperty("sex"));

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值