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

在Java中将InputStream转换为字节数组,java,bytearray,inputstream,Java,Bytearray,Inputstream,如何将整个InputStream读取到字节数组中?您需要从InputStream中读取每个字节,然后将其写入ByteArrayOutputStream 然后,您可以通过调用toByteArray()来检索底层字节数组: 您可以使用Apache来处理此任务和类似任务 IOUtils类型有一个静态方法来读取InputStream并返回字节[] InputStream is; byte[] bytes = IOUtils.toByteArray(is); 这会在内部创建一个ByteArrayOutp

如何将整个
InputStream
读取到字节数组中?

您需要从
InputStream
中读取每个字节,然后将其写入
ByteArrayOutputStream

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

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

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

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

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

您真的需要将图像作为
字节[]
?在
字节[]
中,您希望看到什么?图像文件的完整内容(以图像文件的任何格式编码)或RGB像素值

这里的其他答案向您展示了如何将文件读入
字节[]
。您的
字节[]
将包含文件的确切内容,您需要对其进行解码才能处理图像数据

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

BufferedImage image = ImageIO.read(new File("image.jpg"));
这将为您提供一个
buffereImage
,而不是
字节[]
。要获取图像数据,可以在
buffereImage
上调用
getRaster()
。这将为您提供一个
graster
对象,该对象具有访问像素数据的方法(它具有多个
getPixel()
/
getPixels()
方法)

查找
javax.imageio.imageio
java.awt.image.buffereImage
java.awt.image.Raster
等的API文档

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


另请参阅以下教程:

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

从复制的代码(是的,非常冗长,但需要的内存大小只有其他解决方案的一半。)

//以字节数组的形式返回文件的内容。
公共静态字节[]getBytesFromFile(文件文件)引发IOException{
InputStream is=新文件InputStream(文件);
//获取文件的大小
long length=file.length();
//不能使用长类型创建数组。
//它必须是int类型。
//在转换为int类型之前,请检查
//以确保文件不大于Integer.MAX_值。
if(长度>整数最大值){
//文件太大
}
//创建字节数组以保存数据
字节[]字节=新字节[(int)长度];
//读入字节
整数偏移=0;
int numRead=0;
while(偏移量=0){
偏移量+=numRead;
}
//确保已读入所有字节
if(偏移量<字节长度){
抛出新IOException(“无法完全读取文件”+file.getName());
}
//关闭输入流并返回字节
is.close();
返回字节;
}

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


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

我试图编辑@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();
顺便说一句,ByteArrayOutputStream无需关闭。try/finally为了可读性省略了结构

如果您碰巧使用了,它将非常简单:

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();
}
byte[] bytes = ByteStreams.toByteArray(inputStream);

如果不想使用Apache commons io库,则此代码段取自sun.misc.IOUtils类。它的速度几乎是使用ByteBuffers的常见实现的两倍:

public static byte[] readFully(InputStream is, int length, boolean readAll)
        throws IOException {
    byte[] output = {};
    if (length == -1) length = Integer.MAX_VALUE;
    int pos = 0;
    while (pos < length) {
        int bytesToRead;
        if (pos >= output.length) { // Only expand when there's no room
            bytesToRead = Math.min(length - pos, output.length + 1024);
            if (output.length < pos + bytesToRead) {
                output = Arrays.copyOf(output, pos + bytesToRead);
            }
        } else {
            bytesToRead = output.length - pos;
        }
        int cc = is.read(output, pos, bytesToRead);
        if (cc < 0) {
            if (readAll && length != Integer.MAX_VALUE) {
                throw new EOFException("Detect premature EOF");
            } else {
                if (output.length != pos) {
                    output = Arrays.copyOf(output, pos);
                }
                break;
            }
        }
        pos += cc;
    }
    return output;
}
publicstaticbyte[]已准备就绪(InputStream为,int-length,boolean readAll)
抛出IOException{
字节[]输出={};
如果(长度==-1)长度=Integer.MAX_值;
int pos=0;
while(pos=output.length){//仅在没有空间时展开
bytesToRead=Math.min(长度-pos,output.length+1024);
if(output.length
这是一个优化版本,它尽量避免复制数据字节:

private static byte[] loadStream (InputStream stream) throws IOException {
   int available = stream.available();
   int expectedSize = available > 0 ? available : -1;
   return loadStream(stream, expectedSize);
}

private static byte[] loadStream (InputStream stream, int expectedSize) throws IOException {
   int basicBufferSize = 0x4000;
   int initialBufferSize = (expectedSize >= 0) ? expectedSize : basicBufferSize;
   byte[] buf = new byte[initialBufferSize];
   int pos = 0;
   while (true) {
      if (pos == buf.length) {
         int readAhead = -1;
         if (pos == expectedSize) {
            readAhead = stream.read();       // test whether EOF is at expectedSize
            if (readAhead == -1) {
               return buf;
            }
         }
         int newBufferSize = Math.max(2 * buf.length, basicBufferSize);
         buf = Arrays.copyOf(buf, newBufferSize);
         if (readAhead != -1) {
            buf[pos++] = (byte)readAhead;
         }
      }
      int len = stream.read(buf, pos, buf.length - pos);
      if (len < 0) {
         return Arrays.copyOf(buf, pos);
      }
      pos += len;
   }
}
私有静态字节[]加载流(InputStream流)引发IOException{
int available=stream.available();
int expectedSize=可用>0?可用:-1;
返回加载流(流,预期大小);
}
私有静态字节[]loadStream(InputStream stream,int expectedSize)引发IOException{
int basicBufferSize=0x4000;
int initialBufferSize=(expectedSize>=0)?expectedSize:basicBufferSize;
字节[]buf=新字节[initialBufferSize];
int pos=0;
while(true){
如果(位置==基本长度){
int readAhead=-1;
如果(位置==预期大小){
readAhead=stream.read();//测试EOF是否为expectedSize
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();
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (true) {
    int r = in.read(buffer);
    if (r == -1) break;
    out.write(buffer, 0, r);
}

byte[] ret = out.toByteArray();
byte[] bytes = ByteStreams.toByteArray(inputStream);
public static byte[] readFully(InputStream is, int length, boolean readAll)
        throws IOException {
    byte[] output = {};
    if (length == -1) length = Integer.MAX_VALUE;
    int pos = 0;
    while (pos < length) {
        int bytesToRead;
        if (pos >= output.length) { // Only expand when there's no room
            bytesToRead = Math.min(length - pos, output.length + 1024);
            if (output.length < pos + bytesToRead) {
                output = Arrays.copyOf(output, pos + bytesToRead);
            }
        } else {
            bytesToRead = output.length - pos;
        }
        int cc = is.read(output, pos, bytesToRead);
        if (cc < 0) {
            if (readAll && length != Integer.MAX_VALUE) {
                throw new EOFException("Detect premature EOF");
            } else {
                if (output.length != pos) {
                    output = Arrays.copyOf(output, pos);
                }
                break;
            }
        }
        pos += cc;
    }
    return output;
}
private static byte[] loadStream (InputStream stream) throws IOException {
   int available = stream.available();
   int expectedSize = available > 0 ? available : -1;
   return loadStream(stream, expectedSize);
}

private static byte[] loadStream (InputStream stream, int expectedSize) throws IOException {
   int basicBufferSize = 0x4000;
   int initialBufferSize = (expectedSize >= 0) ? expectedSize : basicBufferSize;
   byte[] buf = new byte[initialBufferSize];
   int pos = 0;
   while (true) {
      if (pos == buf.length) {
         int readAhead = -1;
         if (pos == expectedSize) {
            readAhead = stream.read();       // test whether EOF is at expectedSize
            if (readAhead == -1) {
               return buf;
            }
         }
         int newBufferSize = Math.max(2 * buf.length, basicBufferSize);
         buf = Arrays.copyOf(buf, newBufferSize);
         if (readAhead != -1) {
            buf[pos++] = (byte)readAhead;
         }
      }
      int len = stream.read(buf, pos, buf.length - pos);
      if (len < 0) {
         return Arrays.copyOf(buf, pos);
      }
      pos += len;
   }
}
/**
 * method converts {@link InputStream} Object into byte[] array.
 * 
 * @param stream the {@link InputStream} Object.
 * @return the byte[] array representation of received {@link InputStream} Object.
 * @throws IOException if an error occurs.
 */
public static byte[] streamToByteArray(InputStream stream) throws IOException {

    byte[] buffer = new byte[1024];
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    int line = 0;
    // read bytes from stream, and store them in buffer
    while ((line = stream.read(buffer)) != -1) {
        // Writes bytes from byte array (buffer) into output stream.
        os.write(buffer, 0, line);
    }
    stream.close();
    os.flush();
    os.close();
    return os.toByteArray();
}
/**
         * Begin setup TCP connection to PC app
         * to open integrate connection between mobile app and pc app (or mobile app)
         */
        mSocket = new Socket(IP, port);
       // mSocket.setSoTimeout(30000);

        DataOutputStream mDos = new DataOutputStream(mSocket.getOutputStream());

        String str = "MobileRequest#" + params[0] + "#<EOF>";

        mDos.write(str.getBytes());

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        /* Since data are accepted as byte, all of them will be collected in the
        following byte array which initialised with accepted data length. */
        DataInputStream mDis = new DataInputStream(mSocket.getInputStream());
        byte[] data = new byte[mDis.available()];

        // Collecting data into byte array
        for (int i = 0; i < data.length; i++)
            data[i] = mDis.readByte();

        // Converting collected data in byte array into String.
        String RESPONSE = new String(data);
// Read the file contents into a byte[] array
byte[] buf = new byte[inputStreamLength];
int bytesRead = Math.max(0, inputStream.read(buf));

// If needed: for safety, truncate the array if the file may somehow get
// truncated during the read operation
byte[] contents = bytesRead == inputStreamLength ? buf
                  : Arrays.copyOf(buf, bytesRead);
public static byte[] toByteArray(InputStream is) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            byte[] b = new byte[4096];
            int n = 0;
            while ((n = is.read(b)) != -1) {
                output.write(b, 0, n);
            }
            return output.toByteArray();
        } finally {
            output.close();
        }
    }
@SuppressWarnings("empty-statement")
public static byte[] inputStreamToByte(InputStream is) throws IOException {
    if (is == null) {
        return null;
    }
    // Define a size if you have an idea of it.
    ByteArrayOutputStream r = new ByteArrayOutputStream(2048);
    byte[] read = new byte[512]; // Your buffer size.
    for (int i; -1 != (i = is.read(read)); r.write(read, 0, i));
    is.close();
    return r.toByteArray();
}
import sun.misc.IOUtils;
...
InputStream in = ...;
byte[] buf = IOUtils.readFully(in, -1, false);
InputStream is;
…
byte[] array = is.readAllBytes();
public int readFully(InputStream in, byte[] data) throws IOException {
    int offset = 0;
    int bytesRead;
    boolean read = false;
    while ((bytesRead = in.read(data, offset, data.length - offset)) != -1) {
        read = true;
        offset += bytesRead;
        if (offset >= data.length) {
            break;
        }
    }
    return (read) ? offset : -1;
}
InputStream in = ...;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
in.transferTo( bos );
byte[] bytes = bos.toByteArray();
 byte[] data = new byte[(int) file.length()];
 DataInputStream dis = new DataInputStream(new FileInputStream(file));
 dis.readFully(data);
 dis.close();
 InputStream is = new FileInputStream(file);
 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
 int nRead;
 byte[] data = new byte[(int) file.length()];
 while ((nRead = is.read(data, 0, data.length)) != -1) {
     buffer.write(data, 0, nRead);
 }
 RandomAccessFile raf = new RandomAccessFile(file, "r");
 byte[] data = new byte[(int) raf.length()];
 raf.readFully(data);
private static byte[] readFully(InputStream input) throws IOException {
    try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
        return buffer.lines().collect(Collectors.joining("\n")).getBytes(<charset_can_be_specified>);
    }
}
byte[] array = new BytesOf(stream).bytes();
import org.apache.commons.io.IOUtils;
is = s3object.getObjectContent();
content =IOUtils.toByteArray(is);
import com.amazonaws.util.IOUtils;
is = s3object.getObjectContent();
content =IOUtils.toByteArray(is);
 final byte[] bytes;
 try (inputStream) {
     bytes = inputStream.readAllBytes();
 }
 public static byte[] readAllBytes(InputStream inputStream) throws IOException {
     final int bufLen = 4 * 0x400; // 4KB
     byte[] buf = new byte[bufLen];
     int readLen;
     IOException exception = null;

     try {
         try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
             while ((readLen = inputStream.read(buf, 0, bufLen)) != -1)
                 outputStream.write(buf, 0, readLen);

             return outputStream.toByteArray();
         }
     } catch (IOException e) {
         exception = e;
         throw e;
     } finally {
         if (exception == null) inputStream.close();
         else try {
             inputStream.close();
         } catch (IOException e) {
             exception.addSuppressed(e);
         }
     }
 }
 @Throws(IOException::class)
 fun InputStream.readAllBytes(): ByteArray {
     val bufLen = 4 * 0x400 // 4KB
     val buf = ByteArray(bufLen)
     var readLen: Int = 0

     ByteArrayOutputStream().use { o ->
         this.use { i ->
             while (i.read(buf, 0, bufLen).also { readLen = it } != -1)
                 o.write(buf, 0, readLen)
         }

         return o.toByteArray()
     }
 }
def readAllBytes(inputStream: InputStream): Array[Byte] =
  Stream.continually(inputStream.read).takeWhile(_ != -1).map(_.toByte).toArray
    fun InputStream.readBytesWithSize(size: Long): ByteArray? {
        return when {
            size < 0L -> this.readBytes()
            size == 0L -> ByteArray(0)
            size > Int.MAX_VALUE -> null
            else -> {
                val sizeInt = size.toInt()
                val result = ByteArray(sizeInt)
                readBytesIntoByteArray(result, sizeInt)
                result
            }
        }
    }

    fun InputStream.readBytesIntoByteArray(byteArray: ByteArray,bytesToRead:Int=byteArray.size) {
        var offset = 0
        while (true) {
            val read = this.read(byteArray, offset, bytesToRead - offset)
            if (read == -1)
                break
            offset += read
            if (offset >= bytesToRead)
                break
        }
    }
    fun getStreamLengthFromUri(context: Context, uri: Uri): Long {
        context.contentResolver.query(uri, arrayOf(MediaStore.MediaColumns.SIZE), null, null, null)?.use {
            if (!it.moveToNext())
                return@use
            val fileSize = it.getLong(it.getColumnIndex(MediaStore.MediaColumns.SIZE))
            if (fileSize > 0)
                return fileSize
        }
        //if you wish, you can also get the file-path from the uri here, and then try to get its size, using this: https://stackoverflow.com/a/61835665/878126
        FileUtilEx.getFilePathFromUri(context, uri, false)?.use {
            val file = it.file
            val fileSize = file.length()
            if (fileSize > 0)
                return fileSize
        }
        context.contentResolver.openInputStream(uri)?.use { inputStream ->
            if (inputStream is FileInputStream)
                return inputStream.channel.size()
            else {
                var bytesCount = 0L
                while (true) {
                    val available = inputStream.available()
                    if (available == 0)
                        break
                    val skip = inputStream.skip(available.toLong())
                    if (skip < 0)
                        break
                    bytesCount += skip
                }
                if (bytesCount > 0L)
                    return bytesCount
            }
        }
        return -1L
    }
final InputStream input = ...;
final Bytes bytes = new BytesOf(input);
final byte[] array = bytes.asBytes();
Assert.assertArrayEquals(
    array,
    new byte[]{65, 66, 67}
);
final Bytes decoded = new Base64Bytes(
    new BytesBase64(
        new BytesOf(
            new InputStreamOf("XYZ")
        )
    )
);
Assert.assertEquals(new TextOf(decoded).asString(), "XYZ");