本文介绍了在Java中,如何将InputStream转换为字节数组(byte [])?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的背景是.net,我是Java的新手。我正在为我们公司的java团队做一些工作,架构师需要我实现一个带有InputStream(java.io)对象的方法。为了实现方法的目的,我需要将其转换为字节数组。有没有简单的方法呢?

My background is .net, I'm fairly new to Java. I'm doing some work for our company's java team and the architect needs me to implement a method that takes an InputStream (java.io) object. In order to fulfill the method's purpose I need to convert that into a byte array. Is there an easy way to do this?

推荐答案

最简单的方法是创建一个新的 ByteArrayOutputStream ,将字节复制到该字节,然后调用 toByteArray

The simplest way is to create a new ByteArrayOutputStream, copy the bytes to that, and then call toByteArray:

public static byte[] readFully(InputStream input) throws IOException
{
    byte[] buffer = new byte[8192];
    int bytesRead;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    while ((bytesRead = input.read(buffer)) != -1)
    {
        output.write(buffer, 0, bytesRead);
    }
    return output.toByteArray();
}

这篇关于在Java中,如何将InputStream转换为字节数组(byte [])?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 00:40
查看更多