Can someone explain how I can get a file object if I have only a ByteArrayOutputStream
. How to create a file from a ByteArrayOutputStream
?
In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.
Use the FileUtils#readFileToByteArray(File) from Apache Commons IO, and then create the ByteArrayInputStream using the ByteArrayInputStream(byte[]) constructor. Show activity on this post. create a ByteArrayInputStream around the file content, which is now in memory.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With