java序列化与反序列化

来源:互联网 发布:惠州市干部网络 编辑:程序博客网 时间:2024/05/16 05:27


TestSerializable.java

package pack1;import java.io.Serializable;public class TestSerializable {/** * @param args */public static class Object1 implements Serializable{}public static class Object2 implements Serializable{private String a = "test";private String b = "test";private String c = "test";private String d = "test";private String e = "test";private int f = 20;private long  g = 20L;private boolean boo = true;private Object1 obj = new Object1();}}

TestMain.java

package pack1;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import pack1.TestSerializable.Object2;public class TestMain {/** * @param args * @throws IOException  * @throws ClassNotFoundException  */public static void main(String[] args) throws IOException, ClassNotFoundException {// TODO Auto-generated method stubfor(int i=0;i<3;i++){Object2 object = new Object2();long startTime = System.currentTimeMillis();//创建字节数组输出流ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();//将字节数组输出流包装为ObjectOutputStreamObjectOutputStream objectOutput = new ObjectOutputStream(byteOutput);//将对象写入ObjectOutputStreamobjectOutput.writeObject(object);objectOutput.close();byteOutput.close();byte[] bytes = byteOutput.toByteArray();System.out.println("序列化耗时:"+(System.currentTimeMillis()-startTime)+"ms");long startTime2 = System.currentTimeMillis();//创建字节数组输入流ByteArrayInputStream byteIn = new ByteArrayInputStream(bytes);//将字节数组输入流包装为ObjectInputStreamObjectInputStream objectIn = new ObjectInputStream(byteIn);objectIn.readObject();objectIn.close();byteIn.close();System.out.println("反序列化时间:"+(System.currentTimeMillis()-startTime2)+"ms");}}}


0 0