String ext = Util.getExtention(contentType);
final long fileSize = response.getEntity().getContentLength();
+ // TODO バッファをもう少し大きくとる?
final int BUF_SIZE = 1024 * 32;
- BufferedInputStream in = new BufferedInputStream(response.getEntity().getContent());
-
+ BufferedInputStream in = null;
+ BufferedOutputStream out = null;
File file = new File(downloadFile.toString() + "." + ext);
- logger.info("保存します(" + fileSize / 1024 + "KB): " + file.getPath());
- FileOutputStream fos = new FileOutputStream(file);
- BufferedOutputStream out = new BufferedOutputStream(fos);
-
- long downloadSize = 0;
- int i;
- byte[] buffer = new byte[BUF_SIZE];
- while ((i = in.read(buffer)) != -1) {
- out.write(buffer, 0, i);
- downloadSize += i;
- listener.progress(fileSize, downloadSize);
- if (listener.getCancel()) {
- return new GetFlvResult(null, Status.GET_INFO, userName);
+ try {
+ in = new BufferedInputStream(response.getEntity().getContent());
+
+ logger.info("保存します(" + fileSize / 1024 + "KB): " + file.getPath());
+ FileOutputStream fos = new FileOutputStream(file);
+ out = new BufferedOutputStream(fos);
+
+ long downloadSize = 0;
+ int i;
+ byte[] buffer = new byte[BUF_SIZE];
+ while ((i = in.read(buffer)) != -1) {
+ out.write(buffer, 0, i);
+ downloadSize += i;
+ listener.progress(fileSize, downloadSize);
+ if (Thread.interrupted()) {
+ logger.info("中断します");
+ throw new InterruptedException("中断しました");
+ }
+ }
+ } finally {
+ if (out != null) {
+ out.close();
+ }
+ EntityUtils.consume(response.getEntity());
+ if (in != null) {
+ in.close();
}
}
- EntityUtils.consume(response.getEntity());
- out.close();
- in.close();
if (url.toString().contains("low")) {
return new GetFlvResult(file, Status.GET_LOW, userName);
}
void progress(long fileSize, long downloadSize);
/**
- * ユーザスレッドからNicoHttpClientに対してダウンロードのキャンセルを行う場合にtrueを設定してください.
- * @return ダウンロードを中断する場合はtrue.
- */
- public boolean getCancel();
- /**
* 何もしないリスナの実装.
*/
static final ProgressListener EMPTY_LISTENER = new ProgressListener() {
@Override
public void progress(long fileSize, long downloadSize) {
}
-
- @Override
- public boolean getCancel() {
- return false;
- }
};
}