Al Phaba
Al Phaba

Reputation: 6755

Create a file from a ByteArrayOutputStream

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

Upvotes: 98

Views: 209743

Answers (2)

JREN
JREN

Reputation: 3630

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();
}

Upvotes: 35

Suresh Atta
Suresh Atta

Reputation: 121998

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

Upvotes: 176

Related Questions