Java 1.8 及以下等效于 InputStream.readAllBytes()

Flo*_*tis 3 java inputstream java-8

我写了一个程序,得到所有字节来自InputStreamJava的9

InputStream.readAllBytes()
Run Code Online (Sandbox Code Playgroud)

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

Sha*_*057 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 由于您的方法不负责打开“InputStream”,因此不应关闭它——该责任留给调用者。 (4认同)

Mar*_*nik 5

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

除此之外,您可以(无第三方):

byte[] bytes = new byte[(int) file.length()];
DataInputStream dataInputStream = new DataInputStream(new FileInputStream(file));
dataInputStream .readFully(bytes);
Run Code Online (Sandbox Code Playgroud)

或者,如果您不介意使用第三方(Commons IO):


byte[] bytes = IOUtils.toByteArray(is);
Run Code Online (Sandbox Code Playgroud)

番石榴还有助于:

byte[] bytes = ByteStreams.toByteArray(inputStream);
Run Code Online (Sandbox Code Playgroud)

  • 如果是“文件”,您可以使用 [`Files.readAllBytes(file.toPath())`](https://docs.oracle.com/en/java/javase/11/docs/api/java. base/java/nio/file/Files.html#readAllBytes(java.nio.file.Path))(自 Java 7 起)。 (2认同)