【问题标题】:InputStream won't close, or takes forever toInputStream 不会关闭,或者需要永远
【发布时间】:2011-08-12 01:09:19
【问题描述】:

我正在尝试将外部 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() 时,它会挂起。如果我等待 真的 很长时间,它最终会关闭。似乎它仍在下载文件的其余部分。如何避免这种情况并立即关闭流?

【问题讨论】:

    标签: android inputstream audio-streaming bufferedinputstream


    【解决方案1】:

    使用 HTTP,您通常仍然需要读取(并丢弃)整个响应流的其余部分 - 您不能只是关闭。必须消耗整个流。我不确定 Android 的 httpclient 是基于 commons httpclient 3 还是 4 - 使用 4,您可以使用 HttpUriRequest#abort() 提前结束。不知道3有没有这样的选择

    编辑:查了一下,它看起来像 httpclient 3 ,你可以做 httpget.abort()

    【讨论】:

    • 也为我工作。奇怪的是,大多数 Android 实现都不会挂起。到目前为止,我只在 Droid X2 上看到过这个。
    • 在我的 DefaultHttpClient 中止方法中丢失,但 mHttpClient.getConnectionManager().shutdown() 效果很好。
    猜你喜欢
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 2016-02-20
    • 2017-07-22
    • 2011-06-26
    • 2011-11-04
    相关资源
    最近更新 更多