Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an Object to Inputstream

How can I convert the java Object into a InputStream?

like image 473
SRy Avatar asked Feb 13 '12 16:02

SRy


People also ask

What is object InputStream?

An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. ObjectOutputStream and ObjectInputStream can provide an application with persistent storage for graphs of objects when used with a FileOutputStream and FileInputStream respectively.

Is it possible to create a file object from InputStream?

Since Java 7, you can do it in one line even without using any external libraries: Files. copy(inputStream, outputPath, StandardCopyOption.


1 Answers

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());
like image 63
reevesy Avatar answered Oct 18 '22 20:10

reevesy