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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Al Phaba
  • 6,545
  • 12
  • 51
  • 83

2 Answers2

173

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

DMv2
  • 198
  • 1
  • 12
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • 1
    @MarkusMikkolainen yeah ..obviously :) – Suresh Atta Jul 05 '13 at 12:10
  • 9
    Or use java 7 try with resources statement to completely get rid off finally block;) http://stackoverflow.com/questions/2016299/does-java-have-a-using-statement – dimuthu May 05 '15 at 06:19
  • bro what if i dont have "thefilename" , insted i have byte[] stream of that excel, then what is the way? – Danish Jun 23 '20 at 10:40
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();
}
POSTHUMAN
  • 77
  • 5
JREN
  • 3,572
  • 3
  • 27
  • 45