Solved Zip/Unzip method

Discussion in 'Plugin Development' started by Arceus02, Dec 27, 2012.

Thread Status:
Not open for further replies.
  1. Hello world !

    I'm wondering if anyone has a good zip/unzip class. It would be like that :

    public class ZipUtil
    {
    public static void zip(File inpout, File outpout) { }
    public static void unzip(File inpout, File outpout) { }
    }

    I rly have troubles with the Java Zip API (it creates the zip but doesnt put anything in). I would use it to create ZIPs of some world folders.

    Ty :)
     
  2. Offline

    MP5K

    hello Arceus02,
    to unzip you could use that code:
    PHP:
        public void extractZIP(File archive, File destDir) throws IOException {
       
            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            ZipFile zipFile = new ZipFile(archive);
            Enumeration<? extends ZipEntryentries zipFile.entries();
     
            
    byte[] buffer = new byte[16384];
            
    int len;
            while (
    entries.hasMoreElements()) {
              
    ZipEntry entry = (ZipEntryentries.nextElement();
                
    String entryFileName entry.getName();
              
    File dir buildDirectoryHierarchyFor(entryFileNamedestDir);
         
              if (!
    dir.exists()) {
                  
    dir.mkdirs();
              }
         
              if (!
    entry.isDirectory()) {
                  
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(destDirentryFileName)));
                  
    BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                  while ((
    len bis.read(buffer)) > 0) {
                    
    bos.write(buffer0len);
                  }
         
                  
    bos.flush();
                  
    bos.close();
                  
    bis.close();
     
                  }
              }       
            
    zipFile.close();
          }
     
          private 
    File buildDirectoryHierarchyFor(String entryNameFile destDir) {
               
    int lastIndex entryName.lastIndexOf('/');
               
    String internalPathToEntry entryName.substring(0lastIndex 1);
               return new 
    File(destDirinternalPathToEntry);
          }
     
  3. Ty :)

    Finally i got this code :

    Code:
    package com.Arceus02.ClosedCombat.Util;
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
     
    public class ZipUtil
    {
        public static void zip(File inFolder, File outFolder)
        {
            try
            {
                ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(inFolder));
                zipDir(outFolder.getAbsolutePath(), zos);
           
            }
            catch(Exception e)
            {
                System.out.println("Unable to zip : " + e.getMessage());
            }
        }
     
        public static void zipDir(String dir2zip, ZipOutputStream zos)
        {
            try
            {
                //create a new File object based on the directory we have to zip File
                File zipDir = new File(dir2zip);
                //get a listing of the directory content
                String[] dirList = zipDir.list();
                byte[] readBuffer = new byte[2156];
                int bytesIn = 0;
                //loop through dirList, and zip the files
                for(int i=0; i<dirList.length; i++)
                {
                    File f = new File(zipDir, dirList[i]);
                    if(f.isDirectory())
                    {
                        //if the File object is a directory, call this
                        //function again to add its content recursively
                        String filePath = f.getPath();
                        zipDir(filePath, zos);
                        //loop again
                        continue;
                    }
                    //if we reached here, the File object f was not a directory
                    //create a FileInputStream on top of f
                    FileInputStream fis = new FileInputStream(f);
                    // create a new zip entry
                    ZipEntry anEntry = new ZipEntry(f.getName());
                    //place the zip entry in the ZipOutputStream object
                    zos.putNextEntry(anEntry);
                    //now write the content of the file to the ZipOutputStream
                    while((bytesIn = fis.read(readBuffer)) != -1)
                    {
                        zos.write(readBuffer, 0, bytesIn);
                    }
                    //close the Stream
                    fis.close();
                }
            }
            catch (Exception e)
            {
                System.out.println("Unable to zip : " + e.getMessage());
            }
        }
    } 
    Unfortunatly i get : Unable to zip : world (access refused)

    I try your method, but anyway i feel i'll have to do more to access world folders.

    EDIT : MY BAD ! I swap outFolder and inFolder. x'(

    I finally got this :
    Code:
    package com.Arceus02.ClosedCombat.Util;
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
     
    public class ZipUtil
    {
        public static void zip(File inFolder, File outFolder)
        {
            try
            {
                System.out.println(outFolder);
                ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outFolder));
                System.out.println(inFolder);
                zipDir(inFolder.getAbsolutePath(), zos);
             
            }
            catch(Exception e)
            {
                System.out.println("Unable to zip : " + e.getMessage());
            }
        }
     
        public static void zipDir(String dir2zip, ZipOutputStream zos)
        {
            try
            {
                //create a new File object based on the directory we have to zip File 
                File zipDir = new File(dir2zip);
                //get a listing of the directory content
                String[] dirList = zipDir.list();
                byte[] readBuffer = new byte[2156];
                int bytesIn = 0;
                //loop through dirList, and zip the files
                for(int i=0; i<dirList.length; i++)
                {
                    File f = new File(zipDir, dirList[i]);
                    if(f.isDirectory())
                    {
                        //if the File object is a directory, call this
                        //function again to add its content recursively
                        String filePath = f.getPath();
                        zipDir(filePath, zos);
                        //loop again
                        continue;
                    }
                    //if we reached here, the File object f was not a directory
                    //create a FileInputStream on top of f
                    FileInputStream fis = new FileInputStream(f);
                    // create a new zip entry
                    ZipEntry anEntry = new ZipEntry(f.getName());
                    //place the zip entry in the ZipOutputStream object
                    zos.putNextEntry(anEntry);
                    //now write the content of the file to the ZipOutputStream
                    while((bytesIn = fis.read(readBuffer)) != -1)
                    {
                        zos.write(readBuffer, 0, bytesIn);
                    }
                    //close the Stream
                    fis.close();
                }
            }
            catch (Exception e)
            {
                System.out.println("Unable to zip : " + e.getMessage());
            }
        }
    } 
    Thanks for answering :D
    Solved.

    EDIT 2 : Not solved at all, the .zip is "invalid", so it can't be read.

    EDIT 3 : Solved, i forgot to use .flush() and .close().

    Last post :

    best way to zip is :
    Code:
    package com.Arceus02.ClosedCombat.Util;
     
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
     
    public class ZipUsingJavaUtil  
    {
         /*
         * Zip function zip all files and folders
         */
       @SuppressWarnings("finally")
       public static boolean zipFiles(String srcFolder, String destZipFile)
      {
          boolean result=false;
          try
          {
              System.out.println("Program Start zipping the given files");
              /*
               * send to the zip procedure
               */
              zipFolder(srcFolder,destZipFile);
              result=true;
              System.out.println("Given files are successfully zipped");
          }
          catch(Exception e)
          {
              System.out.println("Some Errors happned during the zip process");
          }
          finally
          {
              return result;
          }
      }
      /*
       * zip the folders  
       */
      private static void zipFolder(String srcFolder, String destZipFile) throws Exception
      {
        ZipOutputStream zip = null;
        FileOutputStream fileWriter = null;
        /*
         * create the output stream to zip file result
         */
        fileWriter = new FileOutputStream(destZipFile);
        zip = new ZipOutputStream(fileWriter);
        /*
         * add the folder to the zip
         */
        addFolderToZip("", srcFolder, zip);
        /*
         * close the zip objects
         */
        zip.flush();
        zip.close();
      }
      /*
       * recursively add files to the zip files
       */
      private static void addFileToZip(String path, String srcFile, ZipOutputStream zip,boolean flag)throws Exception 
      {
         /*
          * create the file object for inputs  
          */
        File folder = new File(srcFile);
     
        /*
         * if the folder is empty add empty folder to the Zip file
         */
        if (flag==true)
        {
            zip.putNextEntry(new ZipEntry(path + "/" +folder.getName() + "/"));
        }
        else
        {     /*
             * if the current name is directory, recursively traverse it to get the files
             */
            if (folder.isDirectory() ) 
            {
                /*
                 * if folder is not empty 
                 */
                addFolderToZip(path, srcFile, zip);
            }
            else
            {
               /*
                * write the file to the output
               */
               byte[] buf = new byte[1024];
               int len;
               FileInputStream in = new FileInputStream(srcFile);
               zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
               while ((len = in.read(buf)) > 0) 
                {
                  /*
                   * Write the Result 
                  */
                  zip.write(buf, 0, len);
                }
            }
        }
      }
    /*
     * add folder to the zip file 
     */
     private static void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)
          throws Exception 
     {
        File folder = new File(srcFolder);
     
        /*
         * check the empty folder
         */
        if (folder.list().length == 0)
        {
             System.out.println(folder.getName());  
             addFileToZip(path , srcFolder, zip,true);
        }
        else
        {
            /*
             * list the files in the folder 
             */
            for (String fileName : folder.list())
            {
              if (path.equals(""))
              {
                addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip,false);
              } 
              else 
                 {
                     addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip,false);
                 }
           }
       }
      }
    }
    
    Found on : http://stackoverflow.com/questions/...file-when-using-java-util-zip-zipoutputstream

    Solved forever.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 30, 2016
  4. its not the best way, it doesn't close the stream when there is an error reading it, this is bad behavor, and if this code runs too long, it will crash the server because of the file pointer limit
    Next it it also recreates the stream to write to the zip file every time, instead of reusing it
    It also dont hava javadoc comments like bukkit have, so you cant call its the best
     
  5. If you have someting better post it. I don't have, and i searched a long time to get this. Help everybody giving yours. Saying that is not helping (you're right but you know the most important is that it has to work).
     
Thread Status:
Not open for further replies.

Share This Page