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.

Ankur
  • 50,282
  • 110
  • 242
  • 312

4 Answers4

28

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

 IOUtils.copy(byteArrayInputStream, new FileOutputStream(outputFileName));
Simon Nickerson
  • 42,159
  • 20
  • 102
  • 127
  • 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. – titania424 Apr 05 '11 at 17:44
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();
maneesh
  • 1,092
  • 1
  • 8
  • 11
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);
}
gvaish
  • 9,374
  • 3
  • 38
  • 43
-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.

Phani
  • 5,319
  • 6
  • 35
  • 43