2010-10-18 34 views
7
public static void main(String argv[]) { 
    try { 
     String date = new java.text.SimpleDateFormat("MM-dd-yyyy") 
       .format(new java.util.Date()); 
     File inFolder = new File("Output/" + date + "_4D"); 
     File outFolder = new File("Output/" + date + "_4D" + ".zip"); 
     ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
       new FileOutputStream(outFolder))); 
     BufferedInputStream in = null; 
     byte[] data = new byte[1000]; 
     String files[] = inFolder.list(); 
     for (int i = 0; i < files.length; i++) { 
      in = new BufferedInputStream(new FileInputStream(
        inFolder.getPath() + "/" + files[i]), 1000); 
      out.putNextEntry(new ZipEntry(files[i])); 
      int count; 
      while ((count = in.read(data, 0, 1000)) != -1) { 
       out.write(data, 0, count); 
      } 
      out.closeEntry(); 
     } 
     out.flush(); 
     out.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

Estoy tratando de comprimir una carpeta que contiene subcarpetas. Intentando comprimir la carpeta llamada 10-18-2010_4D. El programa anterior termina con la siguiente excepción. Por favor asesórese sobre cómo solucionar el problema.Comprimir una carpeta que contiene subcarpetas

java.io.FileNotFoundException: Output\10-18-2010_4D\4D (Access is denied) 
    at java.io.FileInputStream.open(Native Method) 
    at java.io.FileInputStream.<init>(Unknown Source) 
    at java.io.FileInputStream.<init>(Unknown Source) 
    at ZipFile.main(ZipFile.java:17) 
+0

El nombre de la carpeta en la excepción y el que ha mencionado son diferentes. – ivorykoder

+0

posible duplicado de [directorios en un archivo zip cuando se usa java.util.zip.ZipOutputStream] (http://stackoverflow.com/questions/740375/directories-in-a-zip-file-when-using-java-util -zip-zipoutputstream) –

Respuesta

5

Es necesario comprobar si el archivo es un directorio porque no se puede pasar directorios con el método postal.

Eche un vistazo a this page que muestra cómo puede comprimir recursivamente un directorio determinado.

+0

Creo que @dogbane es correcto. Ejecuté su código usando un directorio que solo contenía archivos, y funcionó según lo previsto. Tan pronto como agregué un directorio jerarquizado, obtuve la excepción FNF (acceso denegado). –

2

Incluiría el ant task for zipping - es mucho más fácil trabajar con él.

La clase de tarea se puede encontrar aquí: org.apache.tools.ant.taskdefs.Zip (lo usan mediante programación)

+0

¿Puede dar algunos puntos acerca de por qué debemos preferir la tarea de la hormiga para comprimir? – ivorykoder

+1

se hace en 3 líneas de código, y funciona. Compare con lo anterior. – Bozho

+0

@Bozho Pude encontrar muchos archivos jar en la versión más reciente de Ant. ¿Cuál debería usarse para comprimir carpetas? – LGAP

0
private void zipFiles (ArrayList listWithFiles, String zipName) { 
    try { 

     byte[] buffer = new byte[1024]; 

     // create object of FileOutputStream 
     FileOutputStream fout = new FileOutputStream(zipName); 

     // create object of ZipOutputStream from FileOutputStream 
     ZipOutputStream zout = new ZipOutputStream(fout); 

     for (String currentFile : listWithFiles) { 

      // create object of FileInputStream for source file 
      FileInputStream fin = new FileInputStream(currentFile); 

      // add files to ZIP 
      zout.putNextEntry(new ZipEntry(currentFile)); 

      // write file content 
      int length; 

      while ((length = fin.read(buffer)) > 0) { 
       zout.write(buffer, 0, length); 
      } 

      zout.closeEntry(); 

      // close the InputStream 
      fin.close(); 
     } 

     // close the ZipOutputStream 
     zout.close(); 
    } catch (IOException ioe) { 
     System.out.println("IOException :" + ioe); 
    } 
} 
+1

No resuelve el problema de las subcarpetas – Comencau

18

Aquí está el código para crear el archivo ZIP. El archivo creado preserva la estructura original del directorio (si existe).

public static void addDirToZipArchive(ZipOutputStream zos, File fileToZip, String parrentDirectoryName) throws Exception { 
    if (fileToZip == null || !fileToZip.exists()) { 
     return; 
    } 

    String zipEntryName = fileToZip.getName(); 
    if (parrentDirectoryName!=null && !parrentDirectoryName.isEmpty()) { 
     zipEntryName = parrentDirectoryName + "/" + fileToZip.getName(); 
    } 

    if (fileToZip.isDirectory()) { 
     System.out.println("+" + zipEntryName); 
     for (File file : fileToZip.listFiles()) { 
      addDirToZipArchive(zos, file, zipEntryName); 
     } 
    } else { 
     System.out.println(" " + zipEntryName); 
     byte[] buffer = new byte[1024]; 
     FileInputStream fis = new FileInputStream(fileToZip); 
     zos.putNextEntry(new ZipEntry(zipEntryName)); 
     int length; 
     while ((length = fis.read(buffer)) > 0) { 
      zos.write(buffer, 0, length); 
     } 
     zos.closeEntry(); 
     fis.close(); 
    } 
} 

No olvide cerrar los flujos de salida después de llamar a este método. Aquí está el ejemplo:

public static void main(String[] args) throws Exception { 
    FileOutputStream fos = new FileOutputStream("C:\\Users\\vebrpav\\archive.zip"); 
    ZipOutputStream zos = new ZipOutputStream(fos); 
    addDirToZipArchive(zos, new File("C:\\Users\\vebrpav\\Downloads\\"), null); 
    zos.flush(); 
    fos.flush(); 
    zos.close(); 
    fos.close(); 
} 
0

Esto es lo que he escrito. Este ejemplo mantiene la estructura de los archivos y, con eso, evita la excepción de entrada duplicada.

/** 
    * Compress a directory to ZIP file including subdirectories 
    * @param directoryToCompress directory to zip 
    * @param outputDirectory  where to place the compress file 
    */ 
    public void zipDirectory(File directoryToCompress, File outputDirectory){ 
     try { 
      FileOutputStream dest = new FileOutputStream(new File(outputDirectory, directoryToCompress.getName() + ".zip")); 
      ZipOutputStream zipOutputStream = new ZipOutputStream(dest); 

      zipDirectoryHelper(directoryToCompress, directoryToCompress, zipOutputStream); 
      zipOutputStream.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
    } 

    private void zipDirectoryHelper(File rootDirectory, File currentDirectory, ZipOutputStream out) throws Exception { 
     byte[] data = new byte[2048]; 

     File[] files = currentDirectory.listFiles(); 
     if (files == null) { 
      // no files were found or this is not a directory 

     } else { 
      for (File file : files) { 
       if (file.isDirectory()) { 
        zipDirectoryHelper(rootDirectory, file, out); 
       } else { 
        FileInputStream fi = new FileInputStream(file); 
        // creating structure and avoiding duplicate file names 
        String name = file.getAbsolutePath().replace(rootDirectory.getAbsolutePath(), ""); 

        ZipEntry entry = new ZipEntry(name); 
        out.putNextEntry(entry); 
        int count; 
        BufferedInputStream origin = new BufferedInputStream(fi,2048); 
        while ((count = origin.read(data, 0 , 2048)) != -1){ 
         out.write(data, 0, count); 
        } 
        origin.close(); 
       } 
      } 
     } 

    } 
Cuestiones relacionadas