2017-06-30 22 views
0

我正在使用反射來獲取包含字符串作爲值的對象。然後我將此對象轉換爲字節數組並保存到文件。 當我打開文件時,在預期的字符串前面添加了一些額外的字符。將java對象轉換爲字節數組時發生的問題

FileOutputStream fos = new FileOutputStream("C:\\Temp\\test.txt"); 
Object obj = new String("Hello World"); //replaced reflection code with string object ,still not working 
fos.write(toByteArray(obj)); 
fos.close(); 


public static byte[] toByteArray(Object obj) throws IOException { 
     byte[] bytes = null; 
     ByteArrayOutputStream bos = null; 
     ObjectOutputStream oos = null; 
     try { 
      bos = new ByteArrayOutputStream(); 
      oos = new ObjectOutputStream(bos); 
      oos.writeObject(obj); 
      oos.flush(); 
      bytes = bos.toByteArray(); 
     } finally { 
      if (oos != null) { 
       oos.close(); 
      } 
      if (bos != null) { 
       bos.close(); 
      } 
     } 
     return bytes; 
    } 

輸出的文件中:

enter image description here

文件中

預期輸出:

Hello World 

我不知道爲什麼這個額外的字符出現在我的原始字符串的前面,而將對象轉換爲字節數組。你們可以幫我在這裏嗎

回答

1

ObjectOutputStream#writeObject通過序列化的方式將一個對象寫入輸出流。序列化允許開發人員輕鬆地將對象保存在磁盤上或通過網絡傳輸。

https://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html#writeObject(java.lang.Object)

因此,在你的情況下,它存儲了String類的實例,而不是寫的「Hello World」的人物,

我建議您閱讀了上系列化:https://www.tutorialspoint.com/java/java_serialization.htm

1

你正在使用一個java.io.ObjectOutputStream對象在其中寫入一個字符串。
您不會在文件中獲得人類表示形式的輸出,而是字符串的序列化形式。

要獲得在輸出文件中寫入String的人體表示,您應該使用寧可PrintStream並使用方法:public void println(String x)

相關問題