Правильно ли закрываете URLConnection и InputStream?JAVA

Программисты JAVA общаются здесь
Anonymous
Правильно ли закрываете URLConnection и InputStream?

Сообщение Anonymous »

Я видел много разных примеров использования HttpURLConnection + InputStream и их закрытия (или не закрытия) после использования. Это то, что я придумал, чтобы убедиться, что после завершения все закрывается, независимо от того, есть ошибка или нет. Это действительно?:

Код: Выделить всё

HttpURLConnection conn = null;
InputStream is = null;
try {
URL url = new URL("http://example.com");

// (set connection and read timeouts on the connection)
conn = (HttpURLConnection)url.openConnection();

is = new BufferedInputStream(conn.getInputStream());

doSomethingWithInputStream(is);

} catch (Exception ex) {
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
conn.disconnect();
}
}
Спасибо

Подробнее здесь: https://stackoverflow.com/questions/915 ... -correctly

Вернуться в «JAVA»