zip and unzip in java

后端 未结 2 1504
自闭症患者
自闭症患者 2021-01-29 12:38

I know that it is an easy task, but after changing my code it stopped working and I can\'t get it back! I use two functions to zip and unzip, even though what it actually does i

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-29 13:14

    Somehow I got it working, apparently it WAS stream-related... thanks for the help, everyone!

    class zipper
    {
         static byte[] buffer = new byte[4096];
    
         public static void unzip(File zipfile, File outputfolder)  throws Exception
         {
             JarFile zip = new JarFile(zipfile);
    
             Enumeration entries = zip.entries();
             while(entries.hasMoreElements())
             {
                 JarEntry entry = (JarEntry) entries.nextElement();
                 File unzipped = new File(outputfolder,entry.getName());
    
                 if (entry.isDirectory() && !unzipped.exists())
                 {
                     unzipped.mkdirs();
                     continue;
                 }
                 else if (!unzipped.getParentFile().exists())
                     unzipped.getParentFile().mkdirs();
    
                 InputStream in = zip.getInputStream(entry);
                 FileOutputStream fos = new FileOutputStream(unzipped);
    
                 int count;
                 while((count = in.read(buffer, 0, buffer.length)) != -1)
                     fos.write(buffer, 0, count);
    
                 // clean up
                 fos.close();
                 in.close();
             }
       }
    
       public static void zip(File[] infiles, JarOutputStream jos) throws Exception
       {
           zip(infiles,"",jos);
    
           // clean up
           jos.flush();
           jos.close();
       }
    
       public static void zip(File[] infiles, String basefolder, JarOutputStream jos) throws Exception
       {
           for(int i=0; i

提交回复
热议问题