Распаковать файл в Android - PullRequest
2 голосов
/ 28 ноября 2011

При попытке разархивировать zip-файл я получил следующую ошибку

Подпись конца центрального каталога не найдена

Я также попробовал 7zip lib, он отлично работает в простой Java, но на платформе Android.
Я получаю ошибку "зависимая банка не найдена".

try {
            // Initiate the ZipFile
            ZipFile zipFile = new ZipFile(file);
            String destinationPath = destPath;

            // If zip file is password protected then set the password
            if (zipFile.isEncrypted()) {
                zipFile.setPassword(password);
            }

            //Get a list of FileHeader. FileHeader is the header information for all the
            //files in the ZipFile
            List fileHeaderList = zipFile.getFileHeaders();

            // Loop through all the fileHeaders
            for (int i = 0; i < fileHeaderList.size(); i++) {
                FileHeader fileHeader = (FileHeader)fileHeaderList.get(i);
                if (fileHeader != null) {

                    //Build the output file
                    String outFilePath = destinationPath + System.getProperty("file.separator") + fileHeader.getFileName();
                    File outFile = new File(outFilePath);

                    //Checks if the file is a directory
                    if (fileHeader.isDirectory()) {
                        //This functionality is up to your requirements
                        //For now I create the directory
                        outFile.mkdirs();
                        continue;
                    }

                    //Check if the directories(including parent directories)
                    //in the output file path exists
                    File parentDir = outFile.getParentFile();
                    if (!parentDir.exists()) {
                        parentDir.mkdirs();
                    }

                    //Get the InputStream from the ZipFile
                    is = zipFile.getInputStream(fileHeader);
                    //Initialize the output stream
                    os = new FileOutputStream(outFile);

                    int readLen = -1;
                    byte[] buff = new byte[BUFF_SIZE];

                    //Loop until End of File and write the contents to the output stream
                    while ((readLen = is.read(buff)) != -1) {
                        os.write(buff, 0, readLen);
                    }

                    //Please have a look into this method for some important comments
                    closeFileHandlers(is, os);

                    //To restore File attributes (ex: last modified file time, 
                    //read only flag, etc) of the extracted file, a utility class
                    //can be used as shown below
                    UnzipUtil.applyFileAttributes(fileHeader, outFile);

                    System.out.println("Done extracting: " + fileHeader.getFileName());
                } else {
                    System.err.println("fileheader is null. Shouldn't be here");
                } 

// Заголовок файла всегда выдает ошибку

Ответы [ 2 ]

1 голос
/ 19 октября 2016

Никогда не поздно, я полагаю, использование вышеупомянутой расстегивания молнии действительно слишком медленное, поэтому я изменил его

, используя ниже класс

    package com.example.epubdemo;

    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipInputStream;
    import android.util.Log;

    public class DecompressFast {



 private String _zipFile; 
  private String _location; 

  public DecompressFast(String zipFile, String location) { 
    _zipFile = zipFile; 
    _location = location; 

    _dirChecker(""); 
  } 

  public void unzip() { 
    try  { 
      FileInputStream fin = new FileInputStream(_zipFile); 
      ZipInputStream zin = new ZipInputStream(fin); 
      ZipEntry ze = null; 
      while ((ze = zin.getNextEntry()) != null) { 
        Log.v("Decompress", "Unzipping " + ze.getName()); 

        if(ze.isDirectory()) { 
          _dirChecker(ze.getName()); 
        } else { 
          FileOutputStream fout = new FileOutputStream(_location + ze.getName()); 
         BufferedOutputStream bufout = new BufferedOutputStream(fout);
          byte[] buffer = new byte[1024];
          int read = 0;
          while ((read = zin.read(buffer)) != -1) {
              bufout.write(buffer, 0, read);
          }




          bufout.close();

          zin.closeEntry(); 
          fout.close(); 
        } 

      } 
      zin.close(); 


      Log.d("Unzip", "Unzipping complete. path :  " +_location );
    } catch(Exception e) { 
      Log.e("Decompress", "unzip", e); 

      Log.d("Unzip", "Unzipping failed");
    } 

  } 

  private void _dirChecker(String dir) { 
    File f = new File(_location + dir); 

    if(!f.isDirectory()) { 
      f.mkdirs(); 
    } 
  } 


 }

ИСПОЛЬЗОВАНИЕ

// save zip file in your internal storage directly not in any sub folder( if using any sub folder give below path correctly)
 String zipFile = Environment.getExternalStorageDirectory() + "/the_raven.zip"; //your zip name
  String unzipLocation = Environment.getExternalStorageDirectory() + "/unzippedtestNew/"; //your unzip directory name
DecompressFast df= new DecompressFast(zipFile, unzipLocation);
df.unzip();

НЕ ЗАБУДЬТЕ ПРОЧИТАТЬ И НАПИСАТЬ РАЗРЕШЕНИЯ

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
1 голос
/ 28 ноября 2011

Вам не нужны сторонние библиотеки при разархивировании файлов в Android. Посмотрите на это:

http://www.jondev.net/articles/Unzipping_Files_with_Android_%28Programmatically%29

...