Create a file from a ByteArrayOutputStream

Al Phaba picture Al Phaba · Jul 5, 2013 · Viewed 142.2k times · Source

Can someone explain how I can get a file object if I have only a ByteArrayOutputStream. How to create a file from a ByteArrayOutputStream?

Answer

Suresh Atta picture Suresh Atta · Jul 5, 2013

You can do it with using a FileOutputStream and the writeTo method.

ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
    byteArrayOutputStream.writeTo(outputStream);
}

Source: "Creating a file from ByteArrayOutputStream in Java." on Code Inventions