How do I take a ByteArrayInputStream and have its contents saved as a file on the filesystem
Asked Answered
H

4

18

I have an image which is in the form of a ByteArrayInputStream. I want to take this and make it something that I can save to a location in my filesystem.

I've been going around in circles, could you please help me out.

Hols answered 13/5, 2010 at 5:54 Comment(1)
I can't believe how abstruse this task is.Amoroso
T
28

If you are already using Apache commons-io, you can do it with:

 IOUtils.copy(byteArrayInputStream, new FileOutputStream(outputFileName));
Tenderize answered 13/5, 2010 at 6:19 Comment(1)
This is great, but I found that I needed to create the FileoutputStream outside of the call to copy so that I could close it. Some of the IOUtils flush the buffer, but I was having this problem that the output files weren't openable sometimes. Once I added a call to close() on the FileOutputStream, it worked great. Overall, I am SO GLAD I found the IOUtils stuff, I've been using it for other things as well.Mechling
L
7
InputStream in = //your ByteArrayInputStream here
OutputStream out = new FileOutputStream("filename.jpg");

// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
    out.write(buf, 0, len);
}
in.close();
out.close();
Lur answered 13/5, 2010 at 6:0 Comment(0)
T
2

You can use the following code:

ByteArrayInputStream input = getInputStream();
FileOutputStream output = new FileOutputStream(outputFilename);

int DEFAULT_BUFFER_SIZE = 1024;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
long count = 0;
int n = 0;

n = input.read(buffer, 0, DEFAULT_BUFFER_SIZE);

while (n >= 0) {
   output.write(buffer, 0, n);
   n = input.read(buffer, 0, DEFAULT_BUFFER_SIZE);
}
Tush answered 13/5, 2010 at 5:59 Comment(0)
S
-3
    ByteArrayInputStream stream  = <<Assign stream>>;
    byte[] bytes = new byte[1024];
    stream.read(bytes);
    BufferedWriter writer = new BufferedWriter(new FileWriter(new File("FileLocation")));
    writer.write(new String(bytes));
    writer.close();

Buffered Writer will improve performance in writing files compared to FileWriter.

Selfinsurance answered 13/5, 2010 at 10:15 Comment(1)
Writers are for character files, not binary filesMoiramoirai

© 2022 - 2024 — McMap. All rights reserved.