How to download file and correctly handle exceptions?
<p>My method for downloading file. It's a bit simplified, I removed the third argument - DownloadListener, which I use to inform the caller about dowonload progress.</p>

<pre><code>public static boolean downloadFile(String url, File file) {
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.connect();

        FileOutputStream fos = new FileOutputStream(file);
        InputStream is = connection.getInputStream();

        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) &gt; 0) {
            fos.write(buffer, 0, len);
        }

        is.close();
        fos.flush();
        fos.close();
        return true;
    } catch (IOException e) {
        if (file.exists())
            file.delete();
        return false;
    }
}
</code></pre>

<p>I guess that the exceptions are not handled correctly but if I put the close() calls into finally block, they would have to be surrounded by try-catch block which would look very messy. There must be some cleaner way how to correctly download file in Java. Another thing is, should I call <code>connection.disconnect()</code>?</p>
