在 Java 中,如何将 InputStream 转换为字节数组 (byte[])?

In Java, how can I convert an InputStream into a byte array (byte[])?(在 Java 中,如何将 InputStream 转换为字节数组 (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[])?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)