我不确定应该如何做这件事情。任何帮助都将不胜感激。
从输入流中读取并写入ByteArrayOutputStream,然后调用其toByteArray()
方法获取字节数组。
创建一个ByteArrayInputStream以围绕字节数组进行读取。
以下是快速测试:
import java.io.*;
public class Test {
public static void main(String[] arg) throws Throwable {
File f = new File(arg[0]);
InputStream in = new FileInputStream(f);
byte[] buff = new byte[8000];
int bytesRead = 0;
ByteArrayOutputStream bao = new ByteArrayOutputStream();
while((bytesRead = in.read(buff)) != -1) {
bao.write(buff, 0, bytesRead);
}
byte[] data = bao.toByteArray();
ByteArrayInputStream bin = new ByteArrayInputStream(data);
System.out.println(bin.available());
}
}
InputStream is = getMyInputStream();
ByteArrayInputStream bais = new ByteArrayInputStream(IOUtils.toByteArray(is));
IOUtils.toByteArray(is)
而不是is.readAllBytes()
? - mathiasfk或者先将它转换为字节数组,然后再转换为ByteArrayInputStream。
File f = new File(arg[0]);
InputStream in = new FileInputStream(f);
// convert the inpustream to a byte array
byte[] buf = null;
try {
buf = new byte[in.available()];
while (in.read(buf) != -1) {
}
} catch (Exception e) {
System.out.println("Got exception while is -> bytearr conversion: " + e);
}
// now convert it to a bytearrayinputstream
ByteArrayInputStream bin = new ByteArrayInputStream(buf);
使用 Kotlin 和 org.apache.commons.io.IOUtils
v2
就像这样简单:
IOUtils.toByteArray(is).inputStream()
我猜在Java中也是同样的方式。
javax.imageio
类呢? - Powerlord