Java实现Zip文件解压

原创
2017/07/20 17:46
阅读数 534

##1. 两种java实现zip文件解压方式

  • 使用JDK的原生类java.util.zip,上代码:
import java.util.zip.*;
import java.io.*;

public class UnzipTest {
     public static void main(String[] args) {
          if (args.length != 1) {
               System.out.println("请输入正确参数:java UnzipTest 需解压的文件(e.g. d:/test.zip)");
          } else {
               Unzip unzip = new Unzip();
               if (unzip.unzip(args[0])) {
                    System.out.println("文件解压成功。");
               } else {
                    System.out.println("文件解压失败。");
               }
          }    
     }
}

class Unzip {
     public Unzip() {}

     /*
     * @param srcZipFile 需解压的文件名
     * @return  如果解压成功返回true
     */
     public boolean unzip(String srcZipFile) {
          boolean isSuccessful = true;
          try {
               BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcZipFile));
               ZipInputStream zis = new ZipInputStream(bis);

               BufferedOutputStream bos = null;

               //byte[] b = new byte[1024];
               ZipEntry entry = null;
               while ((entry=zis.getNextEntry()) != null) {
                    String entryName = entry.getName();
                    bos = new BufferedOutputStream(new FileOutputStream("d:/" + entryName));
                    int b = 0;
                    while ((b = zis.read()) != -1) {
                         bos.write(b);
                    }
                    bos.flush();
                    bos.close();
               }
               zis.close();
          } catch (IOException e) {
               isSuccessful = false;
          }
          return isSuccessful;
     }
}

这种解压方式会出现中文文件名乱码的问题。

  • 另一种实现zip文件解压的方式,使用 ant.jar 的org.apache.tools.zip包,上代码:
import java.io.*;
import java.util.Enumeration;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.mockito.internal.util.io.IOUtil;

public class Unzip {
    private static final String ENCODE = "UTF-8";
    /*
   * @param zipDir目标文件存放地,zipFile带解压文件
   * @return  如果解压成功返回true
   */
    public static boolean unzip(String zipDir, String zipFile) {
        ZipFile zfile = null;
        InputStream is = null;
        OutputStream os = null;
        try
        {
            zfile = new ZipFile(zipFile);
            Enumeration<?> zList = zfile.getEntries();
            ZipEntry ze = null;
            byte[] buf = new byte[1024];
            while (zList.hasMoreElements())
            {
                ze = (ZipEntry) zList.nextElement();
                if (ze.isDirectory())
                {
                    /*// 获得当前时间
                    DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                    // 转换为字符串
                    String formatDate = format.format(new Date());
                    // 随机生成文件编号
                    int random = new Random().nextInt(10000);*/
                    File f = new File(zipDir + ze.getName());
                    f.mkdir();
                    continue;
                }
                os = new BufferedOutputStream(new FileOutputStream(getRealFileName(zipDir, ze.getName())));
                is = new BufferedInputStream(zfile.getInputStream(ze));
                int readLen = 0;
                while ((readLen = is.read(buf, 0, 1024)) != -1)
                {
                    os.write(buf, 0, readLen);
                }
                IOUtil.closeQuietly(is);
                IOUtil.closeQuietly(os);
            }
            zfile.close();
            return true;
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            IOUtil.closeQuietly(is);
            IOUtil.closeQuietly(os);
            try
            {
                if (null != zfile)
                {
                    zfile.close();
                }
            }
            catch (IOException ex)
            {
                // ignore
                System.out.println(ex);
            }
        }
        return false;
    }
    /**
     * 给定根目录,返回一个相对路径所对应的实际文件名.
     *
     * @param baseDir
     *            指定根目录
     * @param absFileName
     *            相对路径名,来自于ZipEntry中的name
     * @return java.io.File 实际的文件
     */
    public static File getRealFileName(String baseDir, String absFileName)
    {
        String[] dirs = absFileName.split("/");
        File ret = new File(baseDir);
        if (dirs.length > 1)
        {
            for (int i = 0; i < dirs.length - 1; i++)
            {
                ret = new File(ret, dirs[i]);
            }
            if (!ret.exists())
                ret.mkdirs();
            ret = new File(ret, dirs[dirs.length - 1]);
            return ret;
        }
        ret = new File(ret, dirs[dirs.length - 1]);
        return ret;
    }
}

ant.jar的maven依赖

<dependency>
    <groupId>org.apache.ant</groupId>
    <artifactId>ant</artifactId>
    <version>1.10.1</version>
</dependency>

第二种方法可以避免中文文件名乱码的问题。

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
1 收藏
0
分享
返回顶部
顶部