将 InputStream 转换为字节数组的 Java 程序
要理解此示例,您应该具备以下 Java 编程的知识:
示例 1:Java 程序将 InputStream 转换为字节数组
import java.io.InputStream;
import java.util.Arrays;
import java.io.ByteArrayInputStream;
public class Main {
public static void main(String args[]) {
try {
// create an input stream
byte[] input = {1, 2, 3, 4};
InputStream stream = new ByteArrayInputStream(input);
System.out.println("Input Stream: " + stream);
// convert the input stream to byte array
byte[] array = stream.readAllBytes();
System.out.println("Byte Array: " + Arrays.toString(array));
stream.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
输出
Input Stream: [email protected]
Byte Array: [1, 2, 3, 4]
在上面的例子中,我们创建了一个名为 stream
的输入流. 注意行,
byte[] array = stream.readAllBytes();
在这里,该 readAllBytes()
方法返回流中的所有数据并存储在字节数组中。
注意:我们使用了将整个数组转换为字符串的方法 Arrays.toString()
。
示例 2:使用输出流将 InputStream 转换为字节数组
import java.io.InputStream;
import java.util.Arrays;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
public class Main {
public static void main(String args[]) {
try {
// create an input stream
byte[] input = {1, 2, 3, 4};
InputStream stream = new ByteArrayInputStream(input);
System.out.println("Input Stream: " + stream);
// create an output stream
ByteArrayOutputStream output = new ByteArrayOutputStream();
// create a byte array to store input stream
byte[] array = new byte[4];
int i;
// read all data from input stream to array
while ((i = stream.read(array, 0, array.length)) != -1) {
// write all data from array to output
output.write(array, 0, i);
}
byte[] data = output.toByteArray();
// convert the input stream to byte array
System.out.println("Byte Array: " + Arrays.toString(data));
stream.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
输出
Input Stream: [email protected]
Byte Array: [1, 2, 3, 4]
在上面的例子中,我们从数组 input
创建了一个输入流. 注意这一行,
stream.read(array, 0, array.length)
在这里,所有来自 stream
的元素存储在 array
,从索引0开始。然后我们存储所有 array
中的元素到名为 output
的输出流.
output.write(array, 0, i)
最后,我们调用 ByteArrayOutputStream
类的 toByteArray()
方法,将输出流转换为一个名为 data
的字节数组.