刚学的序列化,希望大家喜欢

序列化慢慢看哦

package com.rmq.xuliehuafanxuliehua;

import java.io.Serializable;

//如果一个 类创建的对象需要被序列化,这个类必须实现Serializable接口
//Serializable 是一个标志接口吗,没任何定义 为了告诉JVM该类对象可以被序列化
// 什么时候对象需要被序列化
//1.把文件保存到文件中(存到物理介质)
//2.对象需要在网络上传输
public class Student implements Serializable{

private static final long serialVersionUID = 1L;   //加上这句话更加严谨

private String name;
private String stuNo;
private String claName;

public Student() {
	
}

public Student(String name, String stuNo, String claName) {
	super();
	this.name = name;
	this.stuNo = stuNo;
	this.claName = claName;
}

@Override
public String toString() {
	return "StudentInfo [name=" + name + ", stuNo=" + stuNo + ", claName=" + claName + "]";
}

public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public String getStuNo() {
	return stuNo;
}
public void setStuNo(String stuNo) {
	this.stuNo = stuNo;
}
public String getClaName() {
	return claName;
}
public void setClaName(String claName) {
	this.claName = claName;
}	

}

package com.rmq.xuliehuafanxuliehua;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class TestSerializable {

public static void main(String[] args) {
	writeObject(); //序列化
	readObject();  //反序列化
}
//反序列化
private static void readObject() {
	File file = new File("d:/Student.txt");
	
	try {
		InputStream in = new FileInputStream(file);
		ObjectInputStream oos = new ObjectInputStream(in);
		Student stu = (Student) oos.readObject();
		oos.close();
		System.out.println(stu);     //写了toString方法
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
	}
	
	
	
}
//对象序列化
/**
 * 对象序列化
 * 把对象写入文件:实际写入的是	类名,属性名,属性类型,属性的值
 */
private static void writeObject() {
	Student stu = new Student("张三","123456","一班");
	File file = new File("d:/Student.txt");
	try {
		OutputStream out = new FileOutputStream(file);
		ObjectOutputStream oos = new ObjectOutputStream(out);
		oos.writeObject(stu);
		oos.close();
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	
}

}

第一次写有什么不对的请大家跟我说说哦

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值