【问题标题】:Java 1.8 and below equivalent for InputStream.readAllBytes()等效于 InputStream.readAllBytes() 的 Java 1.8 及更低版本
【发布时间】:2019-11-26 10:55:46
【问题描述】:

我编写了一个程序,它使用 Java 9InputStream 中获取所有字节

InputStream.readAllBytes()

现在,我想将它导出到 Java 1.8 及更低版本。有没有等价的功能?没找到。

【问题讨论】:

标签: java java-8 inputstream


【解决方案1】:

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

【讨论】:

【解决方案2】:

您可以像这样使用旧的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);
        }
    }
}

【讨论】:

  • 由于您的方法不负责打开InputStream,因此不应该关闭它——这个责任留给了调用者。
  • @Slaw 是真的。只是为了掩盖所有的话题。另外,如果调用者在线呢?在这种情况下,您必须从方法中关闭它。
  • 打开资源(或请求其他代码代表它打开资源)的代码负责管理资源(即完成后关闭它)。您的方法没有打开资源,这意味着管理它不是方法的责任。如果调用者打开了资源但未能关闭它,那么这是一个必须由调用者修复的错误。此外,如果调用者不想立即关闭资源怎么办?您的方法在这方面剥夺了调用者的控制权。
  • 当然,您可以设计关闭资源的方法,但必须记录在案。我还希望有一个更类似于 readAllBytesAndClose 的名称。
  • 如果你想关闭传入的InputStream,只需使用try-with-resource,try(InputStream toClose = inputStream) { ... }。您甚至可以将它与已经存在的 try-with-resource 语句结合使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-15
  • 1970-01-01
  • 2017-04-02
  • 1970-01-01
  • 2015-12-18
相关资源
最近更新 更多