我正在尝试下载一个外部mp3到内部存储。但是,我尝试下载的文件很大,所以我尝试以1MB的块下载它们,以便您可以在下载其他文件时开始播放它们。这是我的流代码:
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()时,它挂起了。如果我等待真的很长时间,它最终会关闭。看起来它还在下载文件的其余部分。我如何避免这种情况并立即关闭流?
使用HTTP,您通常仍然需要读取(并丢弃)响应流的其余部分-您不能直接关闭。整个流必须被消耗。我不确定如果Android的httpclient是基于公共httpclient 3或4 - 4你可以使用httpurirequest# abort()提前结束。不确定3是否有这样的选项
编辑:它看起来像httpclient 3,你可以做httpget.abort()