java 序列化 Serializable接口

一 要解决的问题

        1 把一个类写入文件。

        2 从文件中直接读取一个类

二 解决办法

        1 把要写入的类实现serializable接口

        2 使用ObjectInoutStream ObjectOutStream类

三 代码如下

        说明:实体类Person,写入文件测试类,从文件中读取类测试类

        实体类:

import java.io.Serializable;

public class Person implements Serializable{
	private String name;
	private int age;
	private String address;
	
	
	
	public Person() {
		super();
	}
	public Person(String name, int age, String address) {
		super();
		this.name = name;
		this.age = age;
		this.address = address;
	}
	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 getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", address=" + address + "]";
	}
}

        把类写入文件

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

public class ObjectOutputStreamDemo {
	public static void main(String[] args) {
		try {
			ObjectOutputStream obs = new ObjectOutputStream(new FileOutputStream("D:\\test.txt") );
			Person person = new Person("lemonp",22,"哈尔滨工业大学");
			obs.writeObject(person);
			obs.flush();
			System.out.println("序列化完毕");
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

}

        从文件中读出类

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

public class ObjectInputStreamDemo {
	public static void main(String[] args) throws ClassNotFoundException {
		try {
			ObjectInputStream  ois = new ObjectInputStream(new FileInputStream("D:\\test.txt"));
			
			Person person = (Person)ois.readObject();
			System.out.println("序列化完毕:读出的对象信息如下:");
			System.out.println(person);
			
			
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}

四 运行截图

java 序列化 Serializable接口_第1张图片

你可能感兴趣的:(java)