Create a file from a ByteArrayOutputStream
Asked Answered
C

2

98

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

Chaddie answered 5/7, 2013 at 12:6 Comment(0)
A
174

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

Alake answered 5/7, 2013 at 12:8 Comment(3)
@MarkusMikkolainen yeah ..obviously :)Alake
Or use java 7 try with resources statement to completely get rid off finally block;) #2016799Crozier
bro what if i dont have "thefilename" , insted i have byte[] stream of that excel, then what is the way?Kosher
B
35

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();
}
Belgravia answered 5/7, 2013 at 12:21 Comment(4)
Your code won't work with fos in try block. Also, new File() is not required.Hegumen
It's a good thing he added "new File()". It's easier for the reader to know there's a File constructor available.Ylem
This seems to be needed for Android.Mechanistic
Can be improved with fos inside try-with-resources () and dropping the finallyOdaniel

© 2022 - 2024 — McMap. All rights reserved.