IO流序列化,反序列化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40969422/article/details/80304167
序列化和反序列化
ObjectInputStream    反序列化   readObject()--》类型转换
ObjectOutputStream   序列化   writeObject(Object)

常见异常:
NotSerializableException:类没有实现Serializable接口,不可被序列化

transient屏蔽某些敏感字段的序列化

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 测试序列化ObjectOuputStream
 * 反序列化ObjectInputStream
 * @author 77309
 */
public class ObjeceInputTest {
	public static void main(String[] args) {
		Student stu=new Student("小强",16,"男","123456");
		//序列化
		ObjectOutputStream oos=null;
		FileOutputStream fos=null;
		
		//反序列化
		ObjectInputStream ois=null;
		FileInputStream fis=null;
		try {
			fos=new FileOutputStream("D:/student.txt");
			oos=new ObjectOutputStream(fos);
			oos.writeObject(stu);
			
			fis=new FileInputStream("D:/student.txt");
			ois=new ObjectInputStream(fis);
			Student stu1=(Student)ois.readObject();
			System.out.println(stu1.getName()+"-"+stu1.getAge()+"-"+stu1.getSex()+"-"+stu1.getPssdWord());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			try {
				fis.close();
				ois.close();
				fos.close();
				oos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
}
import java.io.Serializable;

public class Student implements Serializable {
	private String name;
	private int age;
	private String sex;
	private transient String pssdWord;
	public Student(String name, int age, String sex) {
		this.name = name;
		this.age = age;
		this.sex = sex;
	}
	public Student(String name, int age, String sex, String pssdWord) {
		this.name = name;
		this.age = age;
		this.sex = sex;
		this.pssdWord = pssdWord;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getPssdWord() {
		return pssdWord;
	}
	public void setPssdWord(String pssdWord) {
		this.pssdWord = pssdWord;
	}
	
}


猜你喜欢

转载自blog.csdn.net/weixin_40969422/article/details/80304167