Java 1.8 及以下版本相当于 InputStream.readAllBytes()

问题描述 投票:0回答:2

我编写了一个程序,它从

Java 9
中的 InputStream 获取所有字节,并使用

InputStream.readAllBytes()

现在,我想将其导出到Java 1.8及以下版本。有等价的功能吗?没找到。

java java-8 inputstream
2个回答
14
投票

这是一种不依赖第三方库即可解决此问题的方法:

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);

9
投票

您可以使用旧的

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);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.