In Java, how can I convert an InputStream into a byte array (byte[])?(在 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[])?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 中,如何将 InputStream 转换为字节数组 (byte[])?
基础教程推荐
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01