1. InputStream -> byte[]
引入 apache.commons.is 包
import org.apache.commons.io.IOUtils;
byte[] bytes = IOUtils.toByteArray(inputStream);
2. byte[] -> InputStream
InputStream inputStream = new ByteArrayInputStream(bytes);
补充知识:byte[]与各种数据类型互相转换示例
在socket开发过程中,通常需要将一些具体的值(这些值可能是各种JAVA类型)转化为byte[]类型,为此我总结了如下这个示例,贴出来,以便经常翻看
public class TestCase {
/**
* short到字节数组的转换.
*/
public static byte[] shortToByte(short number) {
int temp = number;
byte[] b = new byte[2];
for (int i = 0; i < b.length; i++) {
b[i] = new Integer(temp & 0xff).byteValue();// 将最低位保存在最低位
temp = temp >> 8;// 向右移8位
}
return b;
}
/**
* 字节数组到short的转换.
*/
public static short byteToShort(byte[] b) {
short s = 0;
short s0 = (short) (b[0] & 0xff);// 最低位
short s1 = (short) (b[1] & 0xff);
s1 <<= 8;
s = (short) (s0 | s1);
return s;
}
/**
* int到字节数组的转换.
*/
public static byte[] intToByte(int number) {
int temp = number;
byte[] b = new byte[4];
for (int i = 0; i < b.length; i++) {
b[i