如何在 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP