如果从 try-with-resource 返回 InputStream 是安全的

tar*_*rka 1 java return inputstream try-with-resources

它是安全的,从一试,与资源的语句返回一个输入流来处理流的结束,一旦调用者已经消耗了呢?

public static InputStream example() throws IOException {
    ...
    try (InputStream is = ...) {
        return is;
    }
}
Run Code Online (Sandbox Code Playgroud)

icz*_*cza 5

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

看这个例子:

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

输出:

sun.nio.ch.ChannelInputStream@1db9742
sun.nio.ch.ChannelInputStream@1db9742
Run Code Online (Sandbox Code Playgroud)

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

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

输出:

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)
Run Code Online (Sandbox Code Playgroud)