首页 > 编程语言 >java 解压缩文件

java 解压缩文件

时间:2024-02-29 19:46:28浏览次数:28  
标签:null java srcFile 压缩文件 File new fileName out

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();
    }

标签:null,java,srcFile,压缩文件,File,new,fileName,out
From: https://www.cnblogs.com/mengzhao/p/18045278/java-decompression-file-z1l0lxd

相关文章

  • 【JAVA】百度AI接入api使用流程-【黑图像上色】【步骤2】
    前言:根据API文档中java代码,使用idea编辑代码22.1进入网页,找到java代码https://cloud.baidu.com/doc/IMAGEPROCESS/s/Bk3bclns3 2.2新建java项目     2.3创建java类命名为 Colourize(就是刚才在网页里看到的Java代码的类名)  复制java代码  ......
  • JAVA之CompletableFuture
    目录CompletableFuture入门学习内容学习目标课程学习说明1、FuturevsCompletableFuture1.1准备工作1.2Future的局限性1.3CompletableFuture的优势2、创建异步任务2.1runAsync2.2supplyAsync2.3异步任务中的线程池2.4异步编程思想3、异步任务回调3.1thenApply3.2thenA......
  • java基础
    目录java入门知识:一、开发环境二、关系三、变量四、标识符一、标识符命名的规则二、标识符命名规范1、标识符的命名规则:2、标识符的命名规范:3、变量的声明格式,变量的赋值格式,变量的三要素,变量应该注意几点4、java基本数据类型有哪些?5、java程序的开发步骤是什么?五、运算符一、算术......
  • 【JAVA】百度AI接入api使用流程-【黑图像上色】【步骤1】
    前言以【黑白图像上色】为例讲解百度AI接口使用,方便新手小白接入,以超级简单的方式操作百度AI库使用步骤1.创建应用获取AK(APIKey),SK(SecretKey)1.1进入: 百度AI官网,在开放能力下面找到:黑白图像上色 1.2选择:立即使用 1.3在创建新应用下,填写相应的信息。注意:接口选择......
  • Cause: java.sql.SQLException: Thread stack overrun: 266768 bytes used of a 2867
    ###Cause:java.sql.SQLException:Threadstackoverrun:266768bytesusedofa286720bytestack,and20000bytesneeded.Use'mysqld--thread_stack=#'tospecifyabiggerstack.;uncategorizedSQLException;SQLstate[HY000];errorcode[143......
  • java程序设计 - 第二次实验
    【实验目的】继续熟悉Eclipse的使用并尝试编写一个简单的Applet程序【实验过程】编写一个JavaApplet程序,并正在JavaApplet中写两行文字:“这是一个JavaApplet程序”和“我改变了字体”。importjava.applet.*;importjava.awt.*;publicclassJavaAppletextendsApplet......
  • Java注解
    一:元注解:元注解(meta-annotation)是指用来注解其他注解的注解。Java语言中提供了4种元注解,分别是@Retention、@Target、@Inherited和@Documented。它们的作用如下:例如,@Retention有一个属性value,是RetentionPolicy类型的,而RetentionPolicy是一个枚举类型RetentionPolicy有SOURCE、......
  • linux下准确查询正在tomcat下运行的java进程。准确获取正在运行的java进程的PID
    查看当前运行的所有的java进程,命令:【一定要注意,取那个你配置的JAVA_HOME全局变量的那个java进程的PID】ps-ef|grepjava     准确获取定位到tomcat下正在运行的java进程的PID命令:ps-ef|grepjava|grepcatalina|awk'{print$2}' 准确定位到tomcat下......
  • java 替换Map中key的值
    importjava.util.*;importjava.util.stream.Collectors;publicclassMapKeyReplacement{publicstaticvoidmain(String[]args){//假设我们有如下的List<Map<String,String>>List<Map<String,String>>list=Arrays.asL......
  • Java HashMap 详解
    HashMapHashMap继承自AbstractMap,实现了Map接口,基于哈希表实现,元素以键值对的方式存储,允许键和值为null。因为key不允许重复,因此只能有一个键为null。HashMap不能保证放入元素的顺序,它是无序的,和放入的顺序并不相同。HashMap是线程不安全的。1.哈希表哈希表基于数......