我编写了一个程序,它从
Java 9中的
InputStream
获取所有字节,并使用
InputStream.readAllBytes()
现在,我想将其导出到Java 1.8及以下版本。有等价的功能吗?没找到。
这是一种不依赖第三方库即可解决此问题的方法:
inputStream.reset();
byte[] bytes = new byte[inputStream.available()];
DataInputStream dataInputStream = new DataInputStream(inputStream);
dataInputStream.readFully(bytes);
或者如果您不介意使用第三方(Commons IO):
byte[] bytes = IOUtils.toByteArray(is);
番石榴也有帮助:
byte[] bytes = ByteStreams.toByteArray(inputStream);
read
方法,如下所示:
public static byte[] readAllBytes(InputStream inputStream) throws IOException {
final int bufLen = 1024;
byte[] buf = new byte[bufLen];
int readLen;
IOException exception = null;
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
while ((readLen = inputStream.read(buf, 0, bufLen)) != -1)
outputStream.write(buf, 0, readLen);
return outputStream.toByteArray();
} catch (IOException e) {
exception = e;
throw e;
} finally {
if (exception == null) inputStream.close();
else try {
inputStream.close();
} catch (IOException e) {
exception.addSuppressed(e);
}
}
}