菜鸟谈——java解压缩

  • 1.解压rar、zip、gz
  • 2.压缩zip (由于rar压缩源码的算法没有开源,暂未找到解决方法)
  • 3.在指定的zip压缩包中读取指定文件内容
package kmwp.wpcom;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import de.innosystec.unrar.*;
import de.innosystec.unrar.rarfile.FileHeader;

/**
 * @author zzh
 * @desciption 解压缩工具类:
 * 1.解压rar、zip、gz  
 * 2.压缩zip  (由于rar压缩源码的算法没有开源,暂未找到解决方法) 
 * 3.在指定的zip压缩包中读取指定文件内容
 */
@SuppressWarnings({ "rawtypes", "resource" })
public class DeCompressUtil {

    /**
     * 缓冲大小
     */
    private static int BUFFERSIZE = 2 << 10;

    /**
     * 解压rar格式压缩包<br>
     * 支持windows和linux 依赖包:java-unrar-0.3.jar,commons-logging-1.1.1.jar
     * @param sourceRar 源rar文件
     * @param destDir 目标目录
     * @throws Exception
     */
    public static void unrar(String sourceRar, String destDir) throws Exception {
        // 保证文件夹路径最后是"/"或者"\"
        destDir = dealSeparator(sourceRar, destDir);

        Archive archive = null;
        FileOutputStream fos = null;
        try {
            archive = new Archive(new File(sourceRar));
            FileHeader fh = archive.nextFileHeader();
            while (fh != null) {
                if (!fh.isDirectory()) {
                    // 根据不同的操作系统拿到相应的 destDirName 和 destFileName
                    String compressFileName = fh.getFileNameString().trim();
                    String destFileName = "";
                    String destDirName = "";
                    // 非windows系统
                    if (File.separator.equals("/")) {
                        destFileName = destDir + compressFileName.replaceAll("\\\\", "/");
                        destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));
                        // windows系统
                    } else {
                        destFileName = destDir + compressFileName.replaceAll("/", "\\\\");
                        destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));
                    }
                    File dir = new File(destDirName);
                    if (!dir.exists() || !dir.isDirectory()) {
                        dir.mkdirs();
                    }
                    // 解压文件
                    fos = new FileOutputStream(new File(destFileName));
                    archive.extractFile(fh, fos);
                    fos.close();
                    fos = null;
                }
                fh = archive.nextFileHeader();
            }
            archive.close();
        } catch (Exception e) {
            throw e;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (archive != null) {
                try {
                    archive.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 保证文件夹路径最后是"/"或者"\"
     * @FunName:dealSeparator
     */
    private static String dealSeparator(String sourceZip, String destDir) {
        File srcFile = new File(sourceZip);
        if (null == destDir || "".equals(destDir)) {
            destDir = srcFile.getParentFile().getPath();
        }
        // 保证文件夹路径最后是"/"或者"\"
        char lastChar = destDir.charAt(destDir.length() - 1);
        if (lastChar != '/' && lastChar != '\\') {
            destDir += File.separator;
        }
        return destDir;
    }

    /**
     * 解压zip格式压缩包
     * @param sourceZip
     * @param destDir
     * @param encoding 编码格式 默认是GBK
     */
    public static void unzip(String sourceZip, String destDir, String encoding) {
        // 保证文件夹路径最后是"/"或者"\"
        destDir = dealSeparator(sourceZip, destDir);

        if (null == encoding || "".equals(encoding)) {
            encoding = "GBK";
        }

        FileOutputStream fos = null;
        InputStream is = null;
        try {
            Charset charset = Charset.forName(encoding);
            ZipFile zf = new ZipFile(new File(sourceZip), charset);
            Enumeration en = zf.entries();
            while (en.hasMoreElements()) {
                ZipEntry zn = (ZipEntry) en.nextElement();
                if (!zn.isDirectory()) {
                    is = zf.getInputStream(zn);
                    File f = new File(destDir + zn.getName());
                    File file = f.getParentFile();
                    file.mkdirs();
                    fos = new FileOutputStream(destDir + zn.getName());
                    int len = 0;
                    byte bufer[] = new byte[BUFFERSIZE];
                    while (-1 != (len = is.read(bufer))) {
                        fos.write(bufer, 0, len);
                    }
                    fos.close();
                }
            }
        } catch (ZipException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
                if (null != fos) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @FunName:ungz
     * @Description :解压gz压缩包
     * @param sourceZip 
     * @param destDir
     * TODO 
     */
    public static void ungz(String sourceZip, String destDir) {
        File file = new File(sourceZip);
        try {
            GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(file));
            byte[] b = new byte[1024];
            while (gzipInputStream.read(b) != -1){
                System.err.println("读取到的内容");
                System.err.println(new String(b).trim());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @FunName:readZip
     * @Description :在指定的zip压缩包中读取指定的文件的内容
     * @param zipName 压缩文件 
     * @param fileName 文件名
     * @param encoding  编码格式 默认为GBK
     * @return
     * @throws IOException
     */
    public static BufferedReader readZip(String zipName, String fileName, String encoding) throws IOException {
        if (null == zipName || "".equals(zipName)) {
            return null;
        }
        if (null == fileName || "".equals(fileName)) {
            return null;
        }
        if (null == encoding || "".equals(encoding)) {
            encoding = "GBK";
        }
        BufferedReader resultReader = null;
        Charset charset = Charset.forName(encoding);
        ZipFile zipFile = new ZipFile(zipName, charset);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipName));
        ZipInputStream zis = new ZipInputStream(bis, charset);
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                if (!"".equals(entry.getName()) && entry.getName().contains("/")) {
                    if (fileName.equals(entry.getName().substring(entry.getName().lastIndexOf("/") + 1))) {
                        resultReader = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry), charset));
                    }
                }
            }
        }
        return resultReader;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值