是否安全从try-with-resource语句返回输入流,以便在调用者使用它后处理流的关闭?
public static InputStream example() throws IOException {
...
try (InputStream is = ...) {
return is;
}
}
答案 0 :(得分:4)
这是安全的,但它会被关闭,所以我认为它不是特别有用......(你不能重新打开一个封闭的流。)
见这个例子:
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)