<分区>
从 try-with-resource 语句返回输入流以在调用者使用它后处理流的关闭是否安全?
public static InputStream example() throws IOException {
...
try (InputStream is = ...) {
return is;
}
}
<分区>
从 try-with-resource 语句返回输入流以在调用者使用它后处理流的关闭是否安全?
public static InputStream example() throws IOException {
...
try (InputStream is = ...) {
return is;
}
}
最佳答案
它是安全的,但它会被关闭,所以我认为它不是特别有用...(您无法重新打开已关闭的流。)
看这个例子:
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)
关于java - 如果从 try-with-resource 返回一个 InputStream 是安全的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30643556/