How can I convert the java Object into a InputStream?
Asked
Active
Viewed 7.2k times
1 Answers
64
You can use ObjectOutputStream
You write the object (obj in the code below) to the ObjectOutputStream, your object you want to convert to an input stream must implement Serializable.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.flush();
oos.close();
InputStream is = new ByteArrayInputStream(baos.toByteArray());

reevesy
- 3,452
- 1
- 26
- 23
-
its a nice test , but not very convenient to save/retrieve jpeg. – taitelman Mar 09 '15 at 14:52
-
3what if obj is not implementing Serializable interface. – PeaceIsPearl Aug 31 '17 at 12:35
-
1Just add "implements Serializable" to your class. You may also wish to "generate a serializable UUID" as well, most IDEs will do this for you, like eclipse. This is so that when you serialize the object across the wire there are not conflicts with similar objects in memory. – atom88 Apr 14 '20 at 17:51
-
what if the object size is greater than 2gb?https://stackoverflow.com/questions/72331429/convert-object-to-input-stream-in-java – Arun Singhal May 21 '22 at 16:39