我的块代码如下:
URL url = new URL("http://abc.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream());
StringBuilder sb = new StringBuilder();
String str = null;
while (null != (str = reader.readLine())) {
sb = sb.append(str);
}
resStr = sb.toString();
reader.close();
con.disconnect();
我在上面的区块代码中没有关闭两个输入流。
首先是new InputStreamReader()
,第二个是con.getInputStream()
。我有新的两个输入,但我不关闭它们。出于这个原因,它可能是内存泄漏?
注意:我正在使用jdk1.7.0_21
答案 0 :(得分:3)
总结评论:您没有内存泄漏,因为关闭阅读器也将关闭基础流。
使用Java 7时,您可以使用try-with-resource
的魔力URL url = new URL("http://abc.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));)
{
StringBuilder sb = new StringBuilder();
String str = null;
while (null != (str = reader.readLine()))
sb = sb.append(str);
resStr = sb.toString();
}
con.disconnect();