|
| 1 | +package org.javacore.io.serializable; |
| 2 | + |
| 3 | + |
| 4 | +import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream; |
| 5 | + |
| 6 | +import java.io.*; |
| 7 | + |
| 8 | +/** |
| 9 | + * 描述:Java序列化和反序列化的小例子 |
| 10 | + * Created by 子木 on 2016/2/15. |
| 11 | + */ |
| 12 | +public class SerializableT { |
| 13 | + public static void main(String[] args) throws IOException, ClassNotFoundException { |
| 14 | + for (int i = 0;i < 10;i++) { |
| 15 | + AObjcet aObjcet = new AObjcet(); |
| 16 | + long beginTime = System.currentTimeMillis(); |
| 17 | + |
| 18 | + ByteOutputStream byteOutput = new ByteOutputStream(); |
| 19 | + ObjectOutputStream objectOutput = new ObjectOutputStream(byteOutput); |
| 20 | + objectOutput.writeObject(aObjcet); |
| 21 | + objectOutput.close(); |
| 22 | + byteOutput.close(); |
| 23 | + byte[] bytes = byteOutput.toByteArray(); |
| 24 | + System.out.println("Java序列化耗时:" + (System.currentTimeMillis() - beginTime) + "ms"); |
| 25 | + System.out.println("Java序列化后的字节大小为:" + bytes.length); |
| 26 | + |
| 27 | + beginTime = System.currentTimeMillis(); |
| 28 | + ByteArrayInputStream byteInput = new ByteArrayInputStream(bytes); |
| 29 | + ObjectInputStream objectInput = new ObjectInputStream(byteInput); |
| 30 | + objectInput.readObject(); |
| 31 | + objectInput.close(); |
| 32 | + byteInput.close(); |
| 33 | + System.out.println("Java反序列化耗时:" + (System.currentTimeMillis() - beginTime) + "ms"); |
| 34 | + |
| 35 | + } |
| 36 | + } |
| 37 | +} |
| 38 | +class AObjcet implements Serializable { |
| 39 | + private String a = "bysocket"; |
| 40 | + private String b = "likes"; |
| 41 | + private String c = "java"; |
| 42 | + private String d = "world"; |
| 43 | + |
| 44 | + private int i = 100; |
| 45 | + private int j = 10; |
| 46 | + private long m = 100L; |
| 47 | + |
| 48 | + private boolean isA = true; |
| 49 | + private boolean isB = false; |
| 50 | + private boolean isC = false; |
| 51 | + |
| 52 | + private BObject aObject = new BObject(); |
| 53 | + private BObject bObject = new BObject(); |
| 54 | + private BObject cObject = new BObject(); |
| 55 | + private BObject dObject = new BObject(); |
| 56 | + |
| 57 | +} |
| 58 | +class BObject implements Serializable { |
| 59 | + |
| 60 | +} |
0 commit comments