Android - некоторые разархивированные файлы имеют размер 0 (пустые)

Я столкнулся с проблемой распаковки файлов в Android. Вот фрагмент кода:

 public void unzip() { 
try  { 

  FileInputStream fin = new FileInputStream(_zipFile); 
  BufferedInputStream in = new BufferedInputStream(fin);
  ZipInputStream zin = new ZipInputStream(in); 

  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 out = new BufferedOutputStream(fout);

      byte[] buffer = new byte[1024];
      int length;

      while ((length = zin.read(buffer,0,1024)) >= 0) {
          out.write(buffer,0,length);
        }

      /* while ((length = zin.read(buffer))>0) {
          out.write(buffer, 0, length);
          }*/
       /*for (int c = zin.read(); c != -1; c = zin.read()) { 
        fout.write(c); 
       }*/

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

   } 
   zin.close(); 
 } catch(Exception e) { 
   Log.e("Decompress", "unzip", e); 
 } 
}

Файлы меньшего размера (менее 10 КБ) распаковываются как пустые — размер 0 (файлы html, .jpg). Остальные файлы в порядке. Если я использую этот же код, но без буферов, все файлы в порядке - конечно, о распаковке без буферов не может быть и речи, так как это выполняется слишком долго. Файлы хранятся на SD-карте на реальном устройстве. Я уже пытался установить меньший размер буфера (даже новый байт [2]). Заранее спасибо...


person vlatko    schedule 29.08.2012    source источник


Ответы (1)


Вместо этого попробуйте этот код,

    public void doUnzip(String inputZipFile, String destinationDirectory)
        throws IOException {
    int BUFFER = 2048;
    List zipFiles = new ArrayList();
    File sourceZipFile = new File(inputZip);
    File unzipDestinationDirectory = new File(destinationDirectory);
    unzipDestinationDirectory.mkdir();

    ZipFile zipFile;
    // Open Zip file for reading
    zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

    // Create an enumeration of the entries in the zip file
    Enumeration zipFileEntries = zipFile.entries();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
        // grab a zip file entry
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();

        String currentEntry = entry.getName();

        File destFile = new File(unzipDestinationDirectory, currentEntry);
//          destFile = new File(unzipDestinationDirectory, destFile.getName());

        if (currentEntry.endsWith(".zip")) {
            zipFiles.add(destFile.getAbsolutePath());
        }

        // grab file's parent directory structure
        File destinationParent = destFile.getParentFile();

        // create the parent directory structure if needed
        destinationParent.mkdirs();

        try {
            // extract file if not a directory
            if (!entry.isDirectory()) {
                BufferedInputStream is =
                        new BufferedInputStream(zipFile.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte data[] = new byte[BUFFER];

                // write the current file to disk
                FileOutputStream fos = new FileOutputStream(destFile);
                BufferedOutputStream dest =
                        new BufferedOutputStream(fos, BUFFER);

                // read and write until last byte is encountered
                while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, currentByte);
                }
                dest.flush();
                dest.close();
                is.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    zipFile.close();

    for (Iterator iter = zipFiles.iterator(); iter.hasNext();) {
        String zipName = (String)iter.next();
        doUnzip(
            zipName,
            destinationDirectory +
                File.separatorChar +
                zipName.substring(0,zipName.lastIndexOf(".zip"))
        );
    }

}
person Andro Selva    schedule 29.08.2012