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

Java 1.8 and below equivalent for InputStream.readAllBytes()

我编写了一个程序,它从 InputStream in Java 9

中获取所有字节
InputStream.readAllBytes()

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

InputStream.readAllBytes() 可用,因为 java 9 而不是 java 7...

除此之外你可以(没有第三方):

byte[] bytes = new byte[(int) file.length()];
DataInputStream dataInputStream = new DataInputStream(new FileInputStream(file));
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);
        }
    }
}