我的下載文件的方法。這有點簡化,我刪除了第三個參數 - 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