2012-04-23 30 views
-2

我有個人類的數組對象數組的InputStream

Class Person 
{} 

任何人都可以請幫我轉換Person[]陣列的InputStream或字節流?

在此先感謝。

+0

[序列化解釋](http://java.sun.com/developer/technicalArticles/Programming/serialization) – UmNyobe 2012-04-23 09:08:39

+0

感謝您的回覆...基本上我用Person類作爲例子,但是我有一個帶有jar的類,它不是可序列化的。在這種情況下,我不能繼續進行序列化。 – Ritesh 2012-04-23 09:46:32

+0

如果你不能使用序列化,那麼這個問題應該改寫。是的,它之前已經問過:http://stackoverflow.com/questions/239280/which-is-the-best-alternative-for-java-serialization – mindas 2012-04-23 09:53:48

回答

2

爲了能夠將您的對象寫入(串行化)到流中,您的類應該實現Serializable接口。在大多數情況下,你不需要做任何事情,除了加入的類定義中「實現Serializable」條款:

class Person implements Serializable { 
// your class's fields and methods 
} 

然後,當然,你是不是寫輸入流,而是一個輸出流:

Person p = new Person(); 
// some more code here... 
OutputStream os = new FileOutputStream("persons.txt"); // open file as a stream 
os.write(person); // write person object to the stream 
os.close(); // close the stream 

要轉換爲字節數組,你將不得不仍然使用序列:

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
baos.write(person); 
byte[] bytes = baos.toByteArray(); 
+0

謝謝Maksimov,但我不想寫我的對象到一個文件,而不是我想要一個字節數組我也不能添加可序列化,因爲它打包在一個jar文件中。 – Ritesh 2012-04-23 09:49:56

+0

@Ritesh我已經更新了覆蓋字節數組大小寫的答案,但對於對象不可序列化的情況,您必須解決此問題。看到這個例子:http://stackoverflow.com/questions/2563340/how-to-convert-a-non-serializable-object-to-byte-array – maksimov 2012-04-23 09:56:13