首页 > 解决方案 > 从 URL 下载时无法解压缩文件,但从 FTP 下载时有效

问题描述

我正在尝试从 URL 下载电子书并将其解压缩,以进一步显示。虽然相同的解压缩逻辑适用于 FTP 下载,但对于 URL,解压缩方法在下载后什么也不做。

我的书下载调用方法:

     DownloadBook db = new DownloadBook(localFile,"some url",book.key,context,(TaskListener) result -> {

            if (result) {
                   
            runOnUiThread(() -> pBar.setVisibility(View.VISIBLE));

            
                Runnable t = (Runnable) () -> {
                    unzip(localFile.getPath(), b.key.replace(".zip",""), b);
                    isDownloaded = true;
                  
                    //Deleting downlaoded zip file
                    System.out.println("zip file deleted - "+localFile.delete());

                    String urls = localFile.getPath() + "/" + ((b.key).replace(".zip", ""));
                    System.out.println("URL IS " + urls);
                    System.out.println("Going for Display");
                    GlobalVars.title = b.title;
                    Intent intent = new Intent(My_Library.this, DisplayActivity.class);
                    startActivity(intent);//
                };

                t.run();

            } else {
                runOnUiThread(() ->
                {
                    alert = new AlertDialog.Builder(this);

                alert.setTitle("Error");
                alert.setMessage("Could not download. Please try again !")
                        .setCancelable(true)
                        .setNegativeButton("Continue", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(My_Library.this, My_Library.class);
                                startActivity(intent);
                                dialog.cancel();
                            }
                        });

                alert.create();
                alert.show();

            }
                );


            }

        });

zip文件下载方法:

  t = new Thread(new Runnable() {
            @Override
            public void run() {
               
                InputStream input = null;
                OutputStream output = null;
                HttpURLConnection connection = null;
                try {
                    URL url = new URL("some url");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.connect();

                  
                    int fileLength = connection.getContentLength();

                    // download the file
                    input = connection.getInputStream();
                    output = new FileOutputStream(localFile);

                    byte data[] = new byte[4096];
                    long total = 0;
                    int count;
                    while ((count = input.read(data)) != -1) {

                        total += count;
                        // publishing the progress....
                        System.out.println("Total is "+total);

                        if(fileLength>0)
                        {
                            System.out.println("File length is "+fileLength+" local file length is "+localFile.length());
                            percent = (int) (total * 100 / fileLength);
                            System.out.println("FTP_DOWNLOAD bytesTransferred /downloaded -> " + percent);
                            mProgress.setProgress(percent);

                        }
                        output.write(count);
                        output.flush();

                    }

                    mListener.finished(true);
                } catch (Exception e) {
                    e.printStackTrace();
                    mListener.finished(false);
                } finally {
                    try {
                        output.flush();
                        if (output != null)
                            output.close();
                        if (input != null)
                            input.close();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                       connection.disconnect();
                }

解压方法

public void unzip(String _zipFile, String _targetLocation, Book b) {
    pBar.setVisibility(View.VISIBLE);
    GlobalVars.path = _targetLocation;
    _targetLocation = getApplicationContext().getFilesDir().getPath();

    dirChecker(_targetLocation);

    try {
        BufferedInputStream fin = new BufferedInputStream(new FileInputStream(_zipFile));
        ZipInputStream zin = new ZipInputStream(fin);
        ZipEntry ze = null;
        while ((ze = zin.getNextEntry()) != null) {
            System.out.println("Unzipping file -> " + ze.getName());
            //create dir if required while unzipping
            if (ze.isDirectory()) {
                dirChecker(getApplicationContext().getFilesDir().getPath() + "/" + ze.getName());
            } else {
                File f = new File(getApplicationContext().getFilesDir().getPath() + "/" + ze.getName());
                dirChecker(f.getParent());
                long size = f.length();
                BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(new File(String.valueOf(f.getAbsoluteFile()))));

                byte[] buffer = new byte[1024];
                int read = 0;
                while ((read = zin.read(buffer)) != -1) {
                    fout.write(buffer, 0, read);
                }
                zin.closeEntry();
                fout.close();

        }
        zin.close();
    } catch (Exception e) {
        System.out.println(e);
    } 
}

FTP 下载类方法 Unzip 工作得非常好。但是当我尝试从 url 下载时,它只是下载而不是解压缩。

标签: javaandroid

解决方案


您必须更改输出缓冲区写入方法。

所以,而不是,在 zip 下载方法

    output.write(count);

利用,

  output.write(data,0,count);

推荐阅读