Create a file from a ByteArrayOutputStream
165,104
Solution 1
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
Solution 2
You can use a FileOutputStream for this.
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("myFile"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Put data in your baos
baos.writeTo(fos);
} catch(IOException ioe) {
// Handle exception here
ioe.printStackTrace();
} finally {
fos.close();
}
Author by
Al Phaba
Updated on March 28, 2020Comments
-
Al Phaba about 4 years
Can someone explain how I can get a file object if I have only a
ByteArrayOutputStream
. How to create a file from aByteArrayOutputStream
? -
Suresh Atta almost 11 years@MarkusMikkolainen yeah ..obviously :)
-
Ludovic Guillaume about 10 yearsYour code won't work with
fos
intry
block. Also,new File()
is not required. -
dimuthu about 9 yearsOr use java 7 try with resources statement to completely get rid off finally block;) stackoverflow.com/questions/2016299/…
-
Buffalo over 8 yearsIt's a good thing he added "new File()". It's easier for the reader to know there's a File constructor available.
-
Keith Holliday over 7 yearsThis seems to be needed for Android.
-
vikingsteve over 7 yearsCan be improved with fos inside try-with-resources () and dropping the finally
-
Danish almost 4 yearsbro what if i dont have "thefilename" , insted i have byte[] stream of that excel, then what is the way?