我的下载文件的方法。这有点简化,我删除了第三个参数 - DownloadListener,我使用它来通知调用者关于下载进度。如何下载文件并正确处理异常?
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)) > 0) {
fos.write(buffer, 0, len);
}
is.close();
fos.flush();
fos.close();
return true;
} catch (IOException e) {
if (file.exists())
file.delete();
return false;
}
}
我猜测,异常没有被正确处理,但如果我把close()方法调用进入finally块,他们将不得不通过try-catch块这会显得很凌乱包围。必须有一些更清晰的方式来正确地下载Java文件。另一件事是,我应该拨打connection.disconnect()
?
什么是`Colsable`? – 2010-12-06 10:28:16