1:byte[]转换为InputStream
2:InputStream转换为InputStreambyte[]
Java代码
3、InputStream转换为byte[]
InputStream sbs = new ByteArrayInputStream(byte[] buf);
2:InputStream转换为InputStreambyte[]
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100]; //buff用于存放循环读取的临时数据
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in_b = swapStream.toByteArray(); //in_b为转换之后的结果
Java代码
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class ByteToInputStream {
public static final InputStream byte2Input(byte[] buf) {
return new ByteArrayInputStream(buf);
}
public static final byte[] input2byte(InputStream inStream)
throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
return in2b;
}
}
3、InputStream转换为byte[]
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(input, output);
return output.toByteArray();
}
public static int copy(InputStream input, OutputStream output) throws IOException {
long count = copyLarge(input, output);
if (count > Integer.MAX_VALUE) {
return -1;
}
return (int) count;
}
copyLarge()方法不知道引用的那个jar包还是自己写的方法,测试报错。下面提供一个java.io.*的方法,已经测试通过:
try {
<span style="white-space:pre"> </span>FileInputStream inputStream = new FileInputStream(file);
<span style="white-space:pre"> </span>byte[] fileContent = new byte[inputStream.available()];//构建了一个固定长度的byte[]
<span style="white-space:pre"> </span>ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
<span style="white-space:pre"> </span>int rc = 0;
<span style="white-space:pre"> </span>while ((rc = inputStream.read(fileContent, 0, inputStream.available())) > 0) {
<span style="white-space:pre"> </span>swapStream.write(fileContent, 0, rc);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>byte[] in2b = swapStream.toByteArray();//这里的byte[]就是实际需要的
<span style="white-space:pre"> </span>edocBarcodeBean.setFileContent(in2b);
<span style="white-space:pre"> </span>file.delete();
<span style="white-space:pre"> </span>} catch (Exception e) {
<span style="white-space:pre"> </span>e.printStackTrace();
<span style="white-space:pre"> </span>}