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();
}
Share:
165,104
Al Phaba
Author by

Al Phaba

Updated on March 28, 2020

Comments

  • Al Phaba
    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 a ByteArrayOutputStream?

  • Suresh Atta
    Suresh Atta almost 11 years
    @MarkusMikkolainen yeah ..obviously :)
  • Ludovic Guillaume
    Ludovic Guillaume about 10 years
    Your code won't work with fos in try block. Also, new File() is not required.
  • dimuthu
    dimuthu about 9 years
    Or use java 7 try with resources statement to completely get rid off finally block;) stackoverflow.com/questions/2016299/…
  • Buffalo
    Buffalo over 8 years
    It's a good thing he added "new File()". It's easier for the reader to know there's a File constructor available.
  • Keith Holliday
    Keith Holliday over 7 years
    This seems to be needed for Android.
  • vikingsteve
    vikingsteve over 7 years
    Can be improved with fos inside try-with-resources () and dropping the finally
  • Danish
    Danish almost 4 years
    bro what if i dont have "thefilename" , insted i have byte[] stream of that excel, then what is the way?