【问题标题】:Proper use of URLConnection and try-with-resources in Java 8在 Java 8 中正确使用 URLConnection 和 try-with-resources
【发布时间】:2017-09-28 05:08:35
【问题描述】:

如果这段代码 100% 避免内存泄漏或保持套接字打开,我不是 100%:

    public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {

        URLConnection connection = new URL(url).openConnection();

        connection.setReadTimeout(5000);
        connection.setConnectTimeout(8000);

        try (InputStream is = connection.getInputStream()) {

            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);

            JSONObject json = new JSONObject(jsonText);

            return json;
        }
    }

    private static String readAll(Reader rd) throws IOException {

        StringBuilder sb = new StringBuilder();

        int cp;

        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }

        return sb.toString();
    }

我是否也需要将“BufferedReader rd”放入内部第二次尝试中,还是会过时?如果发生读取或连接超时,并且尝试尚未完成怎么办?顺便说一句,为什么 URLConnection 没有 disconnect() 或 close() 函数?

【问题讨论】:

  • 如果您决定将BufferedReader 放在try-with-resources 中,您可以将它放在同一个中。此外,您无需将 InputStream 放入 try-with-resources。
  • 你的意思是像“try (BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")))) {"`?那会更省钱吗?
  • 我认为两者都是安全的。

标签: java bufferedreader urlconnection try-with-resources


【解决方案1】:

Reader 的所有 close 方法最终都会关闭资源。 (请参阅the javadoc。)因此,如果您关闭了InputStream,则实际上不需要关闭BufferedReaderInputStreamReader。但是,更清楚的是,您正在关闭所有资源,并避免编译器警告,如果您仍然关闭它。由于关闭 Reader 会关闭所有底层 Readers 和资源,因此关闭 BufferedReader 将关闭所有内容:

try (BufferedReader rd = new BufferedReader(new InputStreamReader(
        connection.getInputStream()))) {
    return new JSONObject(readAll(rd));
}

所以你只需要在你的 try-with-resources 中声明顶级阅读器。

【讨论】:

    猜你喜欢
    • 2021-08-03
    • 2013-07-13
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 2020-04-30
    • 1970-01-01
    相关资源
    最近更新 更多