文件下载代码下载的文件大于原始文件

时间:2011-09-10 10:07:52

标签: java android file unzip

我正在下载一些.zip文件,但是当我尝试解压缩它们时,我收到“数据错误”..现在我去看了下载的文件,它们比原来大。这可能是错误的原因吗?

下载文件的代码:

URL=intent.getStringExtra("DownloadService_URL");
    FileName=intent.getStringExtra("DownloadService_FILENAME");
    Path=intent.getStringExtra("DownloadService_PATH");

    try{


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

    conexion.connect();
    int lenghtOfFile = conexion.getContentLength();
    lenghtOfFile/=100;

    InputStream input = new BufferedInputStream(url.openStream());
    OutputStream output = new FileOutputStream(Path+FileName);

    byte data[] = new byte[1024];
    long total = 0;

    int count = 0;
    while ((count = input.read(data)) != -1) {
        output.write(data);
        total += count;

        notification.setLatestEventInfo(context, contentTitle, "Starting download " + FileName + " " + (total/lenghtOfFile), contentIntent);
        mNotificationManager.notify(1, notification);
    }


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

Unzip代码:

try {

            String zipFile = Path + FileName;


            FileInputStream fin = new FileInputStream(zipFile);
            ZipInputStream zin = new ZipInputStream(fin);

            ZipEntry ze = null;
            while ((ze = zin.getNextEntry()) != null) {
                UnzipCounter++;
                if (ze.isDirectory()) {
                    dirChecker(ze.getName());
                } else {
                    FileOutputStream fout = new FileOutputStream(Path
                            + ze.getName());
                    while ((Unziplength = zin.read(Unzipbuffer)) > 0) {
                        fout.write(Unzipbuffer, 0, Unziplength);                    
                    }
                    zin.closeEntry();
                    fout.close();

                }

            }
            zin.close();
            File f = new File(zipFile);
            f.delete();
            notification.setLatestEventInfo(context, contentTitle, "File successfully downloaded", contentIntent);
            mNotificationManager.notify(1, notification);

        } catch (Exception e) {

            notification.setLatestEventInfo(context, contentTitle, "Problem in downloading file ", contentIntent);
            mNotificationManager.notify(1, notification);

        }

    }

解压缩进程启动但在提取一些带有该错误的文件后停止..我尝试了另一个.zip文件,我得到CRC失败错误..我用winrar测试了两个.zip文件..

原始文件大小:3.67mb ..下载文件大小:3.93mb

1 个答案:

答案 0 :(得分:1)

您始终将完整的字节数组写入磁盘,而不检查您读取了多少数据。

同样从性能的角度来看,任何< 1500byte(即通常的以太网MTU)都是一个非常糟糕的主意 - 虽然我认为Java无论如何都要缓存,但为什么要冒任何风险。