【发布时间】:2016-01-05 03:12:31
【问题描述】:
I've read 在 try-with-resources 块中初始化的资源仅在该块期间的范围内。
如果是这样,那么这段代码似乎是如何解决这个问题的?
public class Main {
public static void main(String[] args) throws Exception {
final Main main = new Main();
try {
final char[] buffer = new char[10];
StringReader stringReader = main.testStream();
System.out.println(stringReader.read(buffer, 0, 10));
} catch (IOException e) {
System.out.println("expected IOException caught here");
}
try {
HttpResponse response = main.tryResponse();
response.getEntity();
System.out.println("should not reach this line if response is out of scope");
} catch (Exception e) {
System.out.println("why no IOException here?");
}
}
StringReader tryStream() throws IOException {
try (StringReader reader = new StringReader("string")) {
return reader;
}
}
HttpResponse tryResponse() throws IOException {
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://www.google.com");
try (CloseableHttpResponse response = client.execute(request)) {
return response;
}
}
}
在这种情况下,Java 的最佳实践是什么?
【问题讨论】:
-
这段代码应该 . . .不行。真的吗? stackoverflow.com/questions/22947755/…
-
嗯,你会得到一个封闭的
Closeable回来。这与您认为会发生的情况不同吗? -
@RealSkeptic 是的,是的。对于
InputStream,访问关闭的流会引发异常。Closeable对象有没有其他关闭后可以使用的例子?
标签: java httpclient java-7 try-with-resources