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 stub
for(int i=0;i<3;i++){
Object2 object = new Object2();
long startTime = System.currentTimeMillis();
//创建字节数组输出流
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
//将字节数组输出流包装为ObjectOutputStream
ObjectOutputStream objectOutput = new ObjectOutputStream(byteOutput);
//将对象写入ObjectOutputStream
objectOutput.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);
//将字节数组输入流包装为ObjectInputStream
ObjectInputStream objectIn = new ObjectInputStream(byteIn);
objectIn.readObject();
objectIn.close();
byteIn.close();
System.out.println("反序列化时间:"+(System.currentTimeMillis()-startTime2)+"ms");
}
}
}