lunes, 19 de abril de 2010

Zip en java: Comprimir archivos y/o directorios

Ejemplo claro y conciso para hacer un archivo zip con las librerias de java. El siguente código sirve también para hacer un archivo zip de un directorio con todo su contenido, el cual es agregado de manera recursiva.

A continuación copio y pego el código tal cual pero agrego el enlace de donde lo recuperé.
import java.io.*;
import java.util.zip.*;

/**
 * Compresses a file or directory into a Zip archive. Users of the
 * class supply the name of the file or directory as an argument.
 */
public class SimpleZip {

   private static ZipOutputStream zos;

   public static void main(String[] args) {
      //User must specify a directory to compress      




if (args.length < 1) {
         System.out.println("Usage: java SimpleZip directoryName");
         System.exit(0);
      }
      //Get the name of the file or directory to compress.      




String fileName = args[0];
      //Use the makeZip method to create a Zip archive.


try {
         makeZip(fileName);
      }
      //Simply print out any errors we encounter.


catch (Exception e) {
         System.err.println(e);
      }
   }

   /**
    * Creates a Zip archive. If the name of the file passed in is a
    * directory, the directory's contents will be made into a Zip file.
    */
   public static void makeZip(String fileName)
         throws IOException, FileNotFoundException
   {
      File file = new File(fileName);
      zos = new ZipOutputStream(new FileOutputStream(file + ".zip"));
      //Call recursion.


recurseFiles(file);
      //We are done adding entries to the zip archive,


//so close the Zip output stream.


zos.close();
   }

   /**
    * Recurses down a directory and its subdirectories to look for
    * files to add to the Zip. If the current file being looked at
    * is not a directory, the method adds it to the Zip file.
    */
   private static void recurseFiles(File file)
      throws IOException, FileNotFoundException
   {
      if (file.isDirectory()) {
         //Create an array with all of the files and subdirectories         
 //of the current directory.
String[] fileNames = file.list();
         if (fileNames != null) {
            //Recursively add each array entry to make sure that we get
           //subdirectories as well as normal files in the directory.
            for (int i=0; i<filenames.length; i++){ 
  recursefiles(new File(file, fileNames[i]));
            }
         }
      }
      //Otherwise, a file so add it as an entry to the Zip file.      
else {
         byte[] buf = new byte[1024];
         int len;
         //Create a new Zip entry with the file's name.         


ZipEntry zipEntry = new ZipEntry(file.toString());
         //Create a buffered input stream out of the file         


//we're trying to add into the Zip archive.         


FileInputStream fin = new FileInputStream(file);
         BufferedInputStream in = new BufferedInputStream(fin);
         zos.putNextEntry(zipEntry);
         //Read bytes from the file and write into the Zip archive.         


while ((len = in.read(buf)) >= 0) {
            zos.write(buf, 0, len);
         }
         //Close the input stream.         


         in.close();
         //Close this entry in the Zip stream.         


        zos.closeEntry();
      }
   }
}

El método que hace toda la magia es makeZip(String fileName) el cual hace un archivo zip de nombre fileName+".zip" del respectivo archivo o directorio.

Agrego aquí el link donde se recupera esta pieza de codigo, además de que hace una explicación de el uso de las librerias zip y gzip en java. Clic aqui (Ahora pide que te registres para poder acceder al artículo). 

Algo con lo que he tenido complicación es en crear un archivo jar usando estas librerías, no he encontrado como hacer un jar que sea reconocido al momento de agregarlo al classpath y ejecutar la aplicación java, si alguien tiene algún ejemplo al respecto le agradecería cualquier comentario.

Pazzzzzz

4 comentarios:

  1. En mi computador hay muchos zip archivos. Y tengo complicaciones con estos ficheros. Pero he encontrado - reparar archivo zip en el Internet hace algunas jornadas. Despues el instrumento ha recuperado mis files durante un minuto y de balde como he recordado.

    ResponderEliminar
  2. hola, y puedes dar parametro para compresion, por ejemplo que solo comprima de cierta fecha digamos los de hace mas de un mes o algo asi????

    ResponderEliminar
  3. saludos, he implementado un ejemplo similiar que encontre hace algun tiempo, pero tengo problemas, al usarlo en un servidor linux me el sip se crea con toda la estructura de carpetas, es decir si se le indica que la carpeta que debe de comprimir esta es "../applications/etc.../carpaeta a comprimir/"el zip resultante contiene la siguiente estructura
    ..aplications
    -->etc/
    .
    .
    .
    -->carpeta a comprimir
    -->archivos comprimidos

    cuando se ejecuta el ejemplo en windows funciona perfecto solo comprimiendo la carpeta indicada pero al usarlo en un servidor linux crea toda la gerarquia de directorios
    existe alguna solucion?

    ResponderEliminar
  4. Si adentro de la carpeta hay una carpeta vacía, no la crea.

    ResponderEliminar