如何在Java中将输入流转换为字节数组?

Java中的InputStream类提供了read()方法。此方法接受字节数组,并将输入流的内容读取到给定的字节数组。

示例

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
public class StreamToByteArray {
    public static void main(String args[]) throws IOException{    
       InputStream is = new BufferedInputStream(System.in);
       byte [] byteArray = new byte[1024];
       System.out.println("Enter some data");
       is.read(byteArray);      
       String s = new String(byteArray);
       System.out.println("Contents of the byte stream are :: "+ s);
   }  
}

输出结果

Enter some data
hello how are you
Contents of the byte stream are :: hello how are you

替代解决方案

Apache commons提供了一个名为org.apache.commons.io的库,下面是将库添加到项目中的maven依赖项。

<dependency>
    <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.5</version>
</dependency>

该程序包提供了一个称为IOUtils的类。此类的toByteArray()方法接受InputStream对象,并以字节数组的形式返回流中的内容:

示例

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
public class StreamToByteArray2IOUtils {
   public static void main(String args[]) throws IOException{    
      File file = new File("data");
      FileInputStream fis = new FileInputStream(file);
      byte [] byteArray = IOUtils.toByteArray(fis);
      String s = new String(byteArray);
      System.out.println("Contents of the byte stream are :: "+ s);
   }  
}

输出结果

Contents of the byte stream are :: hello how are you