如何获取ByteArrayInputStream并将其内容保存为文件系统上的文件

时间:2010-05-13 05:54:49

标签: java file-io bytearrayinputstream

我有一个ByteArrayInputStream形式的图像。我想采取这种做法,并将其保存到我的文件系统中的某个位置。

我一直在四处走动,你能不能帮助我。

4 个答案:

答案 0 :(得分:16)

如果您已经在使用Apache commons-io,则可以使用:

 IOUtils.copy(byteArrayInputStream, new FileOutputStream(outputFileName));

答案 1 :(得分:6)

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

答案 2 :(得分:2)

您可以使用以下代码:

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

答案 3 :(得分:-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();
与FileWriter相比,

Buffered Writer将提高写入文件的性能。