Visão geral e uso do fluxo de serialização e do fluxo de desserialização

package cn.itcast_07;

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

/*
 * 序列化流:ObjectOutputStream
 *         把对象按照流一样的方式存入文本文件或者再网络中传输。 对象---流数据
 * 反序列化流:ObjectInputStream
 *          把文本文件中的对象数据或者在网络中的流对象还原成对象。流数据---对象  
 * 
 */
public class 序列化流和反序列化流的概述和使用 {
    
    

	public static void main(String[] args) throws IOException, ClassNotFoundException {
    
    
         //由于我们要对对象进行序列化,所以我们先自定义一个类
		 //序列化数据其实就是把对象写到文件
		 writer();
		 reader();
	}

	private static void reader() throws IOException, IOException, ClassNotFoundException {
    
    
		ObjectInputStream ois = new ObjectInputStream(
				new FileInputStream("o.txt"));
		//还原对象
		Object obj = ois.readObject();
		
		//释放资源
		ois.close();
		System.out.println(obj);
	}

	private static void writer() throws IOException, IOException {
    
    
		ObjectOutputStream oss = new ObjectOutputStream(new FileOutputStream("o.txt"));
		
		//创建对象
		Student s1 = new Student("风从龙" , 123);
	    
		//public final void writeObject(object obj)
	    oss.writeObject(s1);
	    
	    //释放资源
	    oss.close();
	}
}

Acho que você gosta

Origin blog.csdn.net/kaszxc/article/details/108805824
Recomendado
Clasificación