外部 mp3 を内部ストレージにダウンロードしようとしています。ただし、ダウンロードしようとしているファイルは大きいため、1 MB のチャンクでダウンロードして、残りのファイルをダウンロードしている間に再生を開始できるようにしています。ここに私のストリームコードがあります:
InputStream is = null;
OutputStream os = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet( url );
HttpResponse response = client.execute( get );
MyLog.d( "Connection established" );
byte[] buffer = new byte[8192];
is = new BufferedInputStream( response.getEntity().getContent(), buffer.length );
os = openFileOutput( filename, MODE_PRIVATE );
int size;
int totalSize = 0;
while (( size = is.read( buffer ) ) != -1 && totalSize < 1048576) {
os.write( buffer, 0, size );
totalSize += size;
}
MyLog.d( "Finished downloading mix - " + totalSize + " bytes" );
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if ( os != null ) {
try {
os.flush();
os.close();
}
catch (IOException e) {
MyLog.e( "Failed to close output stream." );
}
}
if ( is != null ) {
try {
is.close();
}
catch (IOException e) {
MyLog.e( "Failed to close input stream." );
}
}
}
ファイルを正常にダウンロードしますが、finally ステートメントで is.close() に到達すると、ハングします。しばらく待っていると、いずれ閉まります。残りのファイルをまだダウンロードしているようです。これを回避してストリームをすぐに閉じるにはどうすればよいですか?