Java对象输入输出流、Serializable接口

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34195441/article/details/86165993

1、Java Serializable接口
 * 一般操作对象时,对象是存在内存中的,如果希望将对象保存在磁盘上,或者在网络间传输,这是需要将一个对象序列化为字节序列,这个过程叫做对象的序列化操作。java序列化时会保存类的所有信息,包括属性、方法以及继承关系等等,因此完整但是略显臃肿,在网络传输过程中,有很多其他的对象序列化工具。
 * 实现对象的序列化 ObjectOutputStream
 * 反序列化:把磁盘中的对象读出来  ObjectInputStream

2、

1)person类

package objectio;

import java.io.Serializable;

/**
 * Java Serializable接口
 * 序列化接口
 * 实现对象的序列化接口 ObjectOutputStream
 * 反序列化:把磁盘中的对象读出来  ObjectInputStream
 * @author Administrator
 *
 */
//其中序列化的Person类需要实现Serializable接口
public class Person implements Serializable{
	/**
	 * 随机生成序列化id  鼠标移到Person,选择add generated serial version
	 */
	private static final long serialVersionUID = 6537379251769970632L;
	private String userName;
    private int userAge;
	public Person(String userName,int userAge){
		super();
		this.userName=userName;
		this.userAge=userAge;
	}
	@Override
	public String toString() {
		return "Person [userName=" + userName + ", userAge=" + userAge + "]";
	}
	
}

2)测试类

package objectio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
 * 对象输入输出流:对象的磁盘操作
 * @author Administrator
 */
public class TestObjectIo {
	public static void main(String[] args) {
		FileOutputStream fileOut=null;
		ObjectOutputStream out=null;
		FileInputStream fileInput=null;
		ObjectInputStream input=null;
		
		try {
			fileOut=new FileOutputStream("D:\\文件\\hpu_java_code\\day6\\文件\\haha.txt");
			fileInput=new FileInputStream("D:\\文件\\hpu_java_code\\day6\\文件\\haha.txt");
			//对象输出流
			out=new ObjectOutputStream(fileOut);
			//对象输入流
			input=new ObjectInputStream(fileInput);
			//将对象写入磁盘
			out.writeObject(new Person("lala",23));
			//将对象从磁盘中读取出来
			Object obj=input.readObject();
			System.out.println(obj);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			//surround with
			try {
				if(fileOut!=null){
					fileOut.close();
				}
				if(out!=null){
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

猜你喜欢

转载自blog.csdn.net/qq_34195441/article/details/86165993
今日推荐