问题描述
我试图下载一个外部MP3到内部存储。不过,我试图下载该文件是很大的,所以我试图下载他们1MB块,这样你就可以开始打他们,而其余的被下载。这是我流code:
I'm attempting to download an external mp3 into internal storage. However, the files I'm attempting to download are big, so I'm trying to download them in 1MB chunks so that you can begin playing them while the rest is downloaded. Here's my stream code:
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." );
}
}
}
它下载的文件很好,但是当它到达is.close()在最后声明中,它挂起。如果我等待的真正的很长一段时间,它会最终报收。现在看来似乎仍然下载该文件的其余部分。如何避免这一点,并立即关闭该流?
It downloads the file fine, but when it gets to is.close() in the finally statement, it hangs. If I wait a really long time it'll eventually close. It seems like it's still downloading the rest of the file. How do I avoid this and close the stream immediately?
推荐答案
通过HTTP,通常你还是要读(和扔掉)响应流的整个其余的 - 你不能只是关闭。整个流必须被消耗掉。我不知道,如果Android的HttpClient的是基于Commons的HttpClient 3或4 - 与4您可以使用HttpUriRequest#中止()提前结束。不知道3有这样一个选项
With HTTP, You normally still have to read (and throw away) the whole rest of the response stream - you cannot just close. The entire stream must be consumed. I am not sure if Android's httpclient is based on commons httpclient 3 or 4 - with 4 you can use HttpUriRequest#abort() to end early. Not sure if 3 has such an option
编辑:看着它,它看起来像的HttpClient 3,你可以做httpget.abort()
Looked it up and it looks like httpclient 3 , and you can do httpget.abort()
这篇关于的InputStream不会关闭,或需要永远的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!