2014-02-24 60 views
0

我是序列化的新手。序列化奇怪的結果

我試着編寫簡單的代碼。 我得到了奇怪的結果。我不明白。

我有這樣的代碼:

package easybudda.fakesizeof; 

import java.io.*; 

public class FakeSizeOf { 
    public static void main(String[] args) throws IOException { 
     Object[] arr = { new Boolean(true), new Character('ы'), new Integer(13), new Long(69L), new Double(3.14) }; 
     ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 
     ObjectOutputStream objOutStream = new ObjectOutputStream(outStream); 

     for (Object obj : arr) { 
      outStream.reset(); 
      objOutStream.writeObject(obj); 
      objOutStream.flush(); 
      System.out.println(obj.getClass().getSimpleName() + ": " + outStream.size()); 
     } 

     System.out.println("\nUsing predefined methods:"); 
     outStream.reset(); 
     objOutStream.write(13); 
     objOutStream.flush(); 
     System.out.println("write with int as data: " + outStream.size()); 

     outStream.reset(); 
     objOutStream.writeBoolean(false); 
     objOutStream.flush(); 
     System.out.println("writeBoolean: " + outStream.size()); 

     outStream.reset(); 
     objOutStream.writeByte(1); 
     objOutStream.flush(); 
     System.out.println("writeByte: " + outStream.size()); 

     outStream.reset(); 
     objOutStream.writeChar('ы'); 
     objOutStream.flush(); 
     System.out.println("writeChar: " + outStream.size()); 

     outStream.reset(); 
     objOutStream.writeDouble(3.14); 
     objOutStream.flush(); 
     System.out.println("writeDouble: " + outStream.size()); 

     outStream.reset(); 
     objOutStream.writeInt(13); 
     objOutStream.flush(); 
     System.out.println("writeInt: " + outStream.size()); 

     outStream.reset(); 
     objOutStream.writeLong(69L); 
     objOutStream.flush(); 
     System.out.println("writeLong: " + outStream.size()); 
    } 
} 

輸出:

Boolean: 43 
Character: 46 
Integer: 77 
Long: 51 
Double: 53 

Using predefined methods: 
write with int as data: 3 
writeBoolean: 3 
writeByte: 3 
writeChar: 4 
writeDouble: 10 
writeInt: 6 
writeLong: 10 

可有人exlpain這些結果給我嗎?

1.for例如int - 4字節(6輸入) - 爲什麼?

2.爲什麼從數組中獲得如此巨大的值?

+0

1.如何序列INT原始? 2.爲什麼整數從數組 - 77? – gstackoverflow

回答

0

ObjectOutputStream在它寫入的所有內容前加上類型信息。看到Object Serialization Specification,協議章:

由類寫的所有原始數據被緩衝,幷包裹在塊的數據記錄,而不管是否將數據寫入到該流writeObject方法中或直接從外部寫入流一種writeObject方法。

例如,writeInt(13)寫道119,4,0,0,0,13],這意味着

TC_BLOCKDATA,size=4 bytes,0,0,0,13.