Java resource closing

后端 未结 8 1425
一生所求
一生所求 2021-01-12 00:57

I\'m writing an app that connect to a website and read one line from it. I do it like this:

try{
        URLConnection connection = new URL(\"www.example.com         


        
相关标签:
8条回答
  • 2021-01-12 01:43

    Closing the BufferedReader is enough - this closes the underlying reader too.

    Yishai posted a nice pattern for closing the streams (closing might throw another exception).

    0 讨论(0)
  • 2021-01-12 01:43

    I'd use apache commons IO for this, as others have suggested, mainly IOUtils.toString(InputStream) and IOUtils.closeQuietly(InputStream):

    public String readFromUrl(final String url) {
    
        InputStream stream = null; // keep this for finally block
    
        try {
            stream = new URL(url).openConnection().getInputStream();  // don't keep unused locals
            return IOUtils.toString(stream);
        } catch (final IOException e) {
            // handle IO errors here (probably not like this)
            throw new IllegalStateException("Can't read URL " + url, e);
        } finally {
            // close the stream here, if it's null, it will be ignored
            IOUtils.closeQuietly(stream);
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题