Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 610
Ankur Avatar asked May 13 '10 05:05

Ankur


3 Answers

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

 IOUtils.copy(byteArrayInputStream, new FileOutputStream(outputFileName));
like image 181
Simon Nickerson Avatar answered Nov 08 '22 04:11

Simon Nickerson


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();
like image 22
maneesh Avatar answered Nov 08 '22 03:11

maneesh


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);
}
like image 39
gvaish Avatar answered Nov 08 '22 03:11

gvaish