如何在 Java 中将输入流转换为字节数组?
java programming java8object oriented programming更新于 2025/4/22 17:52:17
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