java从输入流中获取数据并返回字节数组示例

时间:2022-08-25 07:43:21

复制代码 代码如下:


import java.io.ByteArrayOutputStream;
import java.io.InputStream;
//从输入流中获取数据并以字节数组返回
public class StreamTool {
    /**
     * 从输入流获取数据
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inputStream) throws Exception{
        byte[] buffer = new byte[1024];
        int len = -1;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1){
            outputStream.write(buffer, 0, len);
        }
        outputStream.close();
        inputStream.close();
        return outputStream.toByteArray();
    }
}