【问题标题】:If it safe to return an InputStream from try-with-resource [duplicate]如果从 try-with-resource 返回 InputStream 是安全的 [重复]
【发布时间】:2015-08-19 01:09:03
【问题描述】:

从 try-with-resource 语句返回输入流以在调用者使用后处理流的关闭是否安全

public static InputStream example() throws IOException {
    ...
    try (InputStream is = ...) {
        return is;
    }
}

【问题讨论】:

  • 一旦你退出函数执行,资源就会超出范围并因此被垃圾收集......总而言之......安全但无用......
  • @CoderNeji 除了你通常无法判断一个未引用的对象何时会被垃圾收集的部分之外,InputStream关闭,而不是垃圾收集(因为还有从方法返回的“实时”引用)。超出范围的是 is 变量,但这是在编译时解决的另一个问题。
  • 感谢您的解释

标签: java return inputstream try-with-resources


【解决方案1】:

它是安全的,但它会被关闭,所以我认为它不是特别有用......(你不能重新打开一个关闭的流。)

看这个例子:

public static void main(String[] argv) throws Exception {
    System.out.println(example());
}

public static InputStream example() throws IOException {
    try (InputStream is = Files.newInputStream(Paths.get("test.txt"))) {
        System.out.println(is);
        return is;
    }
}

输出:

sun.nio.ch.ChannelInputStream@1db9742
sun.nio.ch.ChannelInputStream@1db9742

返回(相同的)输入流(通过引用相同),但它将被关闭。通过将示例修改为:

public static void main(String[] argv) throws Exception {
    InputStream is = example();
    System.out.println(is + " " + is.available());
}

public static InputStream example() throws IOException {
    try (InputStream is = Files.newInputStream(Paths.get("test.txt"))) {
        System.out.println(is + " " + is.available());
        return is;
    }
}

输出:

sun.nio.ch.ChannelInputStream@1db9742 1000000
Exception in thread "main" java.nio.channels.ClosedChannelException
    at sun.nio.ch.FileChannelImpl.ensureOpen(FileChannelImpl.java:109)
    at sun.nio.ch.FileChannelImpl.size(FileChannelImpl.java:299)
    at sun.nio.ch.ChannelInputStream.available(ChannelInputStream.java:116)
    at sandbox.app.Main.main(Main.java:13)

【讨论】:

    猜你喜欢
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 2014-01-06
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 2021-05-13
    相关资源
    最近更新 更多