java 解压缩文件

java 解压缩文件

  1. 解压缩zip文件
    private static final int BUFFER_SIZE = 2 * 1024;

    public static void zipUncompress(String inputFile) throws Exception {
        File srcFile = new File(inputFile);
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        String destDirPath = inputFile.replace(".zip", "");
        ZipFile zipFile = null;
        try {
            // 创建压缩文件对象
            zipFile = new ZipFile(srcFile, Charset.forName("GBK"));
            // 开始解压
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                if (entry.isDirectory()) {
                    File folder = new File(destDirPath + File.separator + entry.getName());
                    if (!folder.getParentFile().exists()) {
                        folder.getParentFile().mkdirs();
                    }
                    folder.mkdirs();
                } else {
                    File targetFile = new File(destDirPath + File.separator + entry.getName());
                    if (!targetFile.getParentFile().exists()) {
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    InputStream is = null;
                    FileOutputStream fos = null;
                    try {
                        is = zipFile.getInputStream(entry);
                        fos = new FileOutputStream(targetFile);
                        int len;
                        byte[] buf = new byte[1024];
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipFile != null) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            srcFile.delete();
        }
    }

    public static void toZip(List<File> srcFiles, HttpServletResponse response,String fileName) throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.reset();
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Access-Control-Allow-Origin","*");
            response.setContentType("application/download");
            response.setCharacterEncoding("UTF-8");
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  1. 解压缩RAR文件,注意现在junrar无法解压rar5的文件,在生成压缩包的时候选择rar4生成
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream; 
  public static void unRar(String path) throws Exception {
        File srcFile = new File(path);
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        System.out.println(path);
        String destDirPath = path.replace(".rar", "");
        Archive archive = new Archive(new FileInputStream(srcFile));
        FileHeader fileHeader = archive.nextFileHeader();
        while (fileHeader != null) {
            if (fileHeader.isDirectory()) {
                fileHeader = archive.nextFileHeader();
                continue;
            }
            String fileName = fileHeader.getFileNameW().isEmpty() ? fileHeader
                    .getFileNameString() : fileHeader.getFileNameW();
            //if (fileName.contains("\\")){
            //    int i = fileName.indexOf("\\");
            //    fileName = fileName.substring(i+1);
            //}
            String fileSeparator = System.getProperty("file.separator");

            if (fileName.contains("\\")) {
                fileName = fileName.replaceAll("\\\\",fileSeparator);
            }
            File out = new File(destDirPath+File.separator + fileName);
            System.out.println(out.getPath());
            if (!out.exists()) {
                if (!out.getParentFile().exists()) {
                    out.getParentFile().mkdirs();
                }
                out.createNewFile();
            }
            FileOutputStream os = new FileOutputStream(out);
            archive.extractFile(fileHeader, os);

            os.close();

            fileHeader = archive.nextFileHeader();
        }
        archive.close();
    }
posted @ 2024-02-29 19:37  meng_zhao  阅读(11)  评论(0编辑  收藏  举报