Java序列化和反序列化

对一个文本文件的序列化

Java对序列化提供了非常方便的支持,在定义类的时候,如果想让对象可以被序列化,必须实现 implements Serializable

比如,对已存在的wang.txt进行序列化,得到的字节输出到wang1.txt文件中

package Serializable;
/*
 * 文本文件的序列化
 */
import java.io.*;

public class test implements Serializable { public static void main(String[] args) throws ClassNotFoundException { File file=new File("D:\wang.txt"); File fi = new File("D:\wang1.txt"); try { file.createNewFile(); } catch(IOException e) { e.printStackTrace(); } try { //序列化 FileOutputStream fos = new FileOutputStream(fi); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(file); oos.flush(); oos.close(); fos.close(); //反序列化 FileInputStream fis = new FileInputStream(fi); ObjectInputStream ois = new ObjectInputStream(fis); File file1= (File) ois.readObject(); //反序列化一个对象 } catch (IOException e) { e.printStackTrace(); } } }
原文地址:https://www.cnblogs.com/Donnnnnn/p/5714149.html