Converts an object into an input stream. - Java java.io

Java examples for java.io:Serializable

Description

Converts an object into an input stream.

Demo Code


import java.io.*;

public class Main{
    public static void main(String[] argv) throws Exception{
        Object theObject = "java2s.com";
        System.out.println(objectToInputStream(theObject));
    }//from   w  ww.  j  a v  a 2s.co  m
    private static final ByteManipulationUtils instance = new ByteManipulationUtils();
    /**
     * Converts an object into an input stream.
     * @param theObject The object to convert into an input stream.
     * @return The InputStream object of theObject
     */
    public static final InputStream objectToInputStream(Object theObject) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(
                    byteArrayOutputStream);

            objectOutputStream.writeObject(theObject);

            objectOutputStream.flush();
            objectOutputStream.close();

            return new ByteArrayInputStream(
                    byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            NAPILogHelper.instance.log("Error converting object "
                    + theObject.getClass().getName()
                    + " to an input stream!");
            e.printStackTrace();
        }

        return null;
    }
    /**
     * Converts a class to a byte array.
     * @param objectToConvert The object to convert to bytes.
     * @return The bytes of objectToConvert
     */
    public static final byte[] toByteArray(Object objectToConvert) {
        InputStream stream = objectToInputStream(objectToConvert);

        if (stream == null) {
            return new byte[0];
        }

        //Code borrowed and modified from https://forums.bukkit.org/threads/tutorial-extreme-beyond-reflection-asm-replacing-loaded-classes.99376/
        //Edits include fixing the formatting to my taste, along with a few renames, and making the error print
        //to the NAPI Log Helper, as well as fixing a bit of bad programming style.

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        try {
            int bytesRead;
            byte[] data = new byte[16384];

            while ((bytesRead = stream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, bytesRead);
            }

            buffer.flush();
        } catch (IOException e) {
            NAPILogHelper.instance.logError("Unable to convert "
                    + objectToConvert.getClass().getName()
                    + " to a byte array!");
            e.printStackTrace();
        }

        return buffer.toByteArray();
    }
}

Related Tutorials