如何从 try-with-resource 语句中关闭资源

Posted

技术标签:

【中文标题】如何从 try-with-resource 语句中关闭资源【英文标题】:how to close the resources from try-with-resource statement 【发布时间】:2017-01-18 12:21:10 【问题描述】:

我已经编写了以下代码,并且运行良好。

  public void  callingTheAPI() throws IOException

    BufferedReader bufferedReader= null;
    CloseableHttpClient httpclient= null;
    CloseableHttpResponse httpResponse= null;

    try 
        httpclient = HttpClients.createDefault();
        HttpGet httpGet= new HttpGet(URL);
        httpGet.addHeader("Authorization","Bearer "+getToken());

        httpResponse=httpclient.execute(httpGet);
        int responseCode= httpResponse.getStatusLine().getStatusCode();
        System.out.println(responseCode);

        bufferedReader= new BufferedReader(new InputStreamReader (httpResponse.getEntity().getContent()));

        StringBuilder stringBuilder= new StringBuilder();
        String line;
        while((line=bufferedReader.readLine())!=null)
            stringBuilder.append(line);

        

        System.out.println(stringBuilder.toString());
     

    catch (ClientProtocolException e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
     
    catch (IOException e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
    

    finally

        if (bufferedReader != null)
            bufferedReader.close();
        

        if(httpResponse != null)
            httpResponse.close();
        
        if (httpclient != null)
            httpclient.close();
        
    


最近我发现从java 7 开始有一个名为try-with-resource 的新功能,它会在语句正确运行后自动关闭资源。如何将以下代码转换为使用 try-with-resource 语句。我做了一点,但我对如何向其中添加所有资源感到困惑。这是代码

public void closeResources()



    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet= new HttpGet(URL);
    httpGet.addHeader("Authorization","Bearer "+getToken());

    CloseableHttpResponse httpResponse=httpclient.execute(httpGet);
    int responseCode= httpResponse.getStatusLine().getStatusCode();
    System.out.println(responseCode);


    try(BufferedReader bufferedReader= new BufferedReader(new InputStreamReader (httpResponse.getEntity().getContent())))
        StringBuilder stringBuilder= new StringBuilder();
        String line;
        while((line=bufferedReader.readLine())!=null)
            stringBuilder.append(line);

        

        System.out.println(stringBuilder.toString()); 


     catch (UnsupportedOperationException e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
     

    catch (IOException e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
    





能否请您帮我转换这段代码,以便它使用try-with-resources 语句。提前致谢

【问题讨论】:

如果已回答,请关闭问题。 【参考方案1】:

使用“;”作为分隔符来分隔您的资源。现在资源将按照其声明的相反顺序关闭,因此:BufferedReader, InputStreamReader、CloseableHttpResponse。

您还可以从方法中返回可关闭的对象,如下例所示,这样您就可以在分配给 try-catch 块之前对其进行修改。

你可以看这个教程来理解多个try-catch-resources。

 public void closeResources()
       try(CloseableHttpResponse httpResponse = createCloseableHttpResponse();
        InputStreamReader reader = new InputStreamReader(httpResponse.getEntity().getContent());
        BufferedReader bufferedReader= new BufferedReader(reader))

        StringBuilder stringBuilder= new StringBuilder();
        String line;
        while((line=bufferedReader.readLine())!=null)
            stringBuilder.append(line);

        

        System.out.println(stringBuilder.toString());


     catch (UnsupportedOperationException | IOException e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
    


private CloseableHttpResponse createCloseableHttpResponse() throws IOException
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet= new HttpGet("");
    httpGet.addHeader("Authorization","Bearer "+getToken());
    return httpclient.execute(httpGet);

【讨论】:

我们在哪里实例化HttpGet 类并为发送令牌等设置标头。 只需创建返回可关闭对象的工厂方法。代码已更新,大家可以看看

以上是关于如何从 try-with-resource 语句中关闭资源的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Java 中对接口对象使用 try-with-resources 语句

Java 7 新的 try-with-resources 语句,自动资源释放

我应该在 try-with-resources 语句中声明每个资源吗?

我应该为每一行日志使用 try-with-resources 语句吗?

java try-with-resource语句使用

try-with-resources语句