If it safe to return an InputStream from try-with-resource(如果从 try-with-resource 返回 InputStream 是安全的)
问题描述
从 try-with-resource 语句返回输入流以在调用者使用后处理流的关闭是否安全?
Is it safe to return an input stream from a try-with-resource statement to handle the closing of the stream once the caller has consumed it?
public static InputStream example() throws IOException {
...
try (InputStream is = ...) {
return is;
}
}
推荐答案
是安全的,但是会被关闭,所以我觉得不是特别有用...(不能重新打开关闭的流.)
It's safe, but it will be closed, so I don't think it is particularly useful... (You can't reopen a closed stream.)
看这个例子:
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
返回(相同的)输入流(通过引用相同),但它将被关闭.通过将示例修改为:
The (same) input stream is returned (same by reference), but it will be closed. By modifying the example to this:
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)
这篇关于如果从 try-with-resource 返回 InputStream 是安全的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果从 try-with-resource 返回 InputStream 是安全的
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01