在 Java 中将 InputStream 转换为字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1264709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 07:35:14  来源:igfitidea点击:

Convert InputStream to byte array in Java

javabytearrayinputstream

提问by JGC

How do I read an entire InputStreaminto a byte array?

如何将整个读InputStream入字节数组?

采纳答案by Rich Seller

You can use Apache Commons IOto handle this and similar tasks.

您可以使用 Apache Commons IO来处理此任务和类似任务。

The IOUtilstype has a static method to read an InputStreamand return a byte[].

IOUtils类型有一个静态方法来读取一个InputStream并返回一个byte[]

InputStream is;
byte[] bytes = IOUtils.toByteArray(is);

Internally this creates a ByteArrayOutputStreamand copies the bytes to the output, then calls toByteArray(). It handles large files by copying the bytes in blocks of 4KiB.

这会在内部创建 aByteArrayOutputStream并将字节复制到输出,然后调用toByteArray(). 它通过复制 4KiB 块中的字节来处理大文件。

回答by Adamski

You need to read each byte from your InputStreamand write it to a ByteArrayOutputStream.

您需要从您的读取每个字节InputStream并将其写入ByteArrayOutputStream.

You can then retrieve the underlying byte array by calling toByteArray():

然后,您可以通过调用来检索底层字节数组toByteArray()

InputStream is = ...
ByteArrayOutputStream buffer = new ByteArrayOutputStream();

int nRead;
byte[] data = new byte[16384];

while ((nRead = is.read(data, 0, data.length)) != -1) {
  buffer.write(data, 0, nRead);
}

return buffer.toByteArray();

回答by firstthumb

Below Codes

下面的代码

public static byte[] serializeObj(Object obj) throws IOException {
  ByteArrayOutputStream baOStream = new ByteArrayOutputStream();
  ObjectOutputStream objOStream = new ObjectOutputStream(baOStream);

  objOStream.writeObject(obj); 
  objOStream.flush();
  objOStream.close();
  return baOStream.toByteArray(); 
} 

OR

或者

BufferedImage img = ...
ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
ImageIO.write(img, "jpeg", baos);
baos.flush();
byte[] result = baos.toByteArray();
baos.close();

回答by Jesper

Do you really need the image as a byte[]? What exactly do you expect in the byte[]- the complete content of an image file, encoded in whatever format the image file is in, or RGB pixel values?

你真的需要图像byte[]吗?您究竟期望什么byte[]- 图像文件的完整内容,以图像文件的任何格式编码,或 RGB 像素值?

Other answers here show you how to read a file into a byte[]. Your byte[]will contain the exact contents of the file, and you'd need to decode that to do anything with the image data.

此处的其他答案向您展示了如何将文件读入byte[]. 您byte[]将包含文件的确切内容,您需要对其进行解码才能对图像数据执行任何操作。

Java's standard API for reading (and writing) images is the ImageIO API, which you can find in the package javax.imageio. You can read in an image from a file with just a single line of code:

Java 用于读取(和写入)图像的标准 API 是 ImageIO API,您可以在包中找到它javax.imageio。您只需一行代码即可从文件中读取图像:

BufferedImage image = ImageIO.read(new File("image.jpg"));

This will give you a BufferedImage, not a byte[]. To get at the image data, you can call getRaster()on the BufferedImage. This will give you a Rasterobject, which has methods to access the pixel data (it has several getPixel()/ getPixels()methods).

这会给你一个BufferedImage,而不是一个byte[]。要获取的图像数据,可以调用getRaster()BufferedImage。这将为您提供一个Raster对象,该对象具有访问像素数据的方法(它有多个getPixel()/getPixels()方法)。

Lookup the API documentation for javax.imageio.ImageIO, java.awt.image.BufferedImage, java.awt.image.Rasteretc.

查找API文档javax.imageio.ImageIOjava.awt.image.BufferedImagejava.awt.image.Raster等。

ImageIO supports a number of image formats by default: JPEG, PNG, BMP, WBMP and GIF. It's possible to add support for more formats (you'd need a plug-in that implements the ImageIO service provider interface).

ImageIO 默认支持多种图像格式:JPEG、PNG、BMP、WBMP 和 GIF。可以添加对更多格式的支持(您需要一个实现 ImageIO 服务提供者接口的插件)。

See also the following tutorial: Working with Images

另请参阅以下教程:使用图像

回答by Aturio

Input Stream is ...
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int next = in.read();
while (next > -1) {
    bos.write(next);
    next = in.read();
}
bos.flush();
byte[] result = bos.toByteArray();
bos.close();

回答by Madhu

/*InputStream class_InputStream = null;
I am reading class from DB 
class_InputStream = rs.getBinaryStream(1);
Your Input stream could be from any source
*/
int thisLine;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((thisLine = class_InputStream.read()) != -1) {
    bos.write(thisLine);
}
bos.flush();
byte [] yourBytes = bos.toByteArray();

/*Don't forget in the finally block to close ByteArrayOutputStream & InputStream
 In my case the IS is from resultset so just closing the rs will do it*/

if (bos != null){
    bos.close();
}

回答by pihentagy

@Adamski: You can avoid buffer entirely.

@Adamski:您可以完全避免使用缓冲区。

Code copied from http://www.exampledepot.com/egs/java.io/File2ByteArray.html(Yes, it is very verbose, but needs half the size of memory as the other solution.)

http://www.exampledepot.com/egs/java.io/File2ByteArray.html复制的代码(是的,它非常冗长,但需要的内存大小是其他解决方案的一半。)

// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);

    // Get the size of the file
    long length = file.length();

    // You cannot create an array using a long type.
    // It needs to be an int type.
    // Before converting to an int type, check
    // to ensure that file is not larger than Integer.MAX_VALUE.
    if (length > Integer.MAX_VALUE) {
        // File is too large
    }

    // Create the byte array to hold the data
    byte[] bytes = new byte[(int)length];

    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
           && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
        offset += numRead;
    }

    // Ensure all the bytes have been read in
    if (offset < bytes.length) {
        throw new IOException("Could not completely read file "+file.getName());
    }

    // Close the input stream and return bytes
    is.close();
    return bytes;
}

回答by dermoritz

Use vanilla Java's DataInputStreamand its readFullyMethod (exists since at least Java 1.4):

使用 vanilla JavaDataInputStream及其readFully方法(至少从 Java 1.4 开始存在):

...
byte[] bytes = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(bytes);
...

There are some other flavors of this method, but I use this all the time for this use case.

这种方法还有其他一些风格,但我一直在这个用例中使用它。

回答by akostadinov

I tried to edit @numan's answer with a fix for writing garbage data but edit was rejected. While this short piece of code is nothing brilliant I can't see any other better answer. Here's what makes most sense to me:

我试图用写入垃圾数据的修复程序来编辑@numan 的答案,但编辑被拒绝。虽然这段简短的代码并不出色,但我看不到任何其他更好的答案。以下是对我来说最有意义的:

ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; // you can configure the buffer size
int length;

while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); //copy streams
in.close(); // call this in a finally block

byte[] result = out.toByteArray();

btw ByteArrayOutputStream need not be closed. try/finally constructs omitted for readability

btw ByteArrayOutputStream 不需要关闭。为了可读性,省略了 try/finally 结构

回答by oliverkn

public static byte[] getBytesFromInputStream(InputStream is) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream(); 
    byte[] buffer = new byte[0xFFFF];
    for (int len = is.read(buffer); len != -1; len = is.read(buffer)) { 
        os.write(buffer, 0, len);
    }
    return os.toByteArray();
}