从android下载文件时出现套接字异常

时间:2013-12-09 10:47:11

标签: android sockets download

我使用下面的代码在android.code中下载zip文件工作正常,但有时下载失败并抛出套接字异常。特别是在互联网连接缓慢的时候(我猜)。我还发布了logcat错误信息的屏幕截图。

int count;

        URL url = new URL(URL);
        URLConnection conexion = url.openConnection();
        conexion.connect();

        int lenghtOfFile = conexion.getContentLength();
        //Log.e("ANDRO_ASYNC", "Lenght of file: " + "="+lenghtOfFile);

        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream(StorezipFileLocation);

        byte data[] = new byte[lenghtOfFile];

        long total = 0;

        while ((count = input.read(data)) != -1) {
            total += c![enter image description here][1]ount;
            publishProgress(""+(int)((total*100)/lenghtOfFile));
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();

enter image description here

2 个答案:

答案 0 :(得分:1)

connection reset by peer通常意味着您正在与一个认为连接已经关闭的同伴交谈。我不明白为什么在关闭FileOutputStream时会发生这种情况。

此外,在您的代码中但在终结器中不会发生异常。是否有可能在出现问题时,您在上层捕获异常并保持连接和文件打开?放弃的连接由最终结果关闭,但为时已晚。

我不确定它是否能解决问题但最好使用finally子句来确保文件和连接正确关闭。

答案 1 :(得分:0)

日志没有说明代码中发生崩溃的位置。是不是还有一些信息没有出现在你的截图中?

它似乎在文件输入流的close方法上失败了。 你可以简单地用try catch块包围对close()的调用,并将你的流设置为null(如果它在关闭时失败)

相关问题