search
HomeJavajavaTutorialCase study of decompressing and compressing folders in Java
Case study of decompressing and compressing folders in JavaOct 16, 2017 am 10:09 AM
javacompressionfolder

This article mainly introduces the relevant information of Java decompression and compressed folder examples. I hope this article can help everyone to realize such functions and master such methods. Friends in need can refer to it

Detailed examples of java decompression and compression folders

Note: JDK7 supports setting encoding and encoding format zipFile, zipInputStream, and zipOutputStream have added encoding formats , if jdk1.6 needs other package assistance

The following is the code for the built-in jdk compressed folder:


##

public void dozip(String srcfile, String zipfile) throws IOException {
  String temp = "";
  File src = new File(srcfile);
  File zipFile=new File(zipfile);
  //判断要压缩的文件存不存在
  if (!src.exists()) {
    System.err.println("要压缩的文件不存在!");
    System.exit(1);
  }
  //如果说压缩路径不存在,则创建
  if (!zipFile.getParentFile().exists()) {
    zipFile.getParentFile().mkdirs();
//   System.out.println("创建ok");
  }
  // 封装压缩的路径
  BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(zipfile));
  //这里可以加入校验
//CheckedOutputStream cos = new CheckedOutputStream(bos,new CRC32());  
  //还可以设置压缩格式,默认UTF-8
  Charset charset = Charset.forName("GBK"); 
  ZipOutputStream zos = new ZipOutputStream(bos,charset);
  zip(src, zos, temp);
  //关闭流
  zos.flush();
  zos.close();
  System.out.println("压缩完成!");
  System.out.println("压缩文件的位置是:" + zipfile);
// System.out.println("检验和:"+cos.getChecksum().getValue());
  }

 private void zip(File file, ZipOutputStream zos, String temp)
    throws IOException {
  // 如果不加"/"将会作为文件处理,空文件夹不需要读写操作
  if (file.isDirectory()) {
    String str = temp + file.getName() + "/";
    zos.putNextEntry(new ZipEntry(str));
    File[] files = file.listFiles();
    for (File file2 : files) {
    zip(file2, zos, str);
    }
  } else {
    // System.out.println("当前文件的父路径:"+temp);
    ZipFile(file, zos, temp);
  }
  }

  private void ZipFile(File srcfile, ZipOutputStream zos, String temp)
    throws IOException {
  // 默认的等级压缩-1
  // zos.setLevel(xxx);
  // 封装待压缩文件
  BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
    srcfile));
  zos.putNextEntry(new ZipEntry(temp + srcfile.getName()));

  byte buf[] = new byte[1024];
  int len;
  while ((len = bis.read(buf)) != -1) {
    zos.write(buf, 0, len);
  }
  //按标准需要关闭当前条目,不写也行
  zos.closeEntry();
  bis.close();
  }

The following is the decompression:


Here are the decompression rules for good compression:


1. If you decompress to a folder with the same name as the compressed file, decompress directly


If you have customized other folder xxx, create xxx first, and then put it into the decompressed folder


2. When Haoyi compresses, it uses the GBK format, so when decompressing , for the sake of unification, GBK decompression is used. Let’s talk about WINRAR. Because RAR compression is patented (commercial software), the RAR compression algorithm is not public, but the decompression algorithm is available, and its compression is also in GBK format by default;

After testing, we found that no matter whether UTF-8 or GBK is used for compression, GBK can be used for decompression correctly! (The specific reason is still unclear)

This java program is decompressed directly to the folder. By default, it is decompressed to the same path as the compressed file.


If there is a problem with the decompression encoding, an error will be reported: java.lang.IllegalArgumentException: MALFORMED


If the compressed file has a password: Error: java.util.zip.ZipException: encrypted ZIP entry not supporte


//方法1:
public void unZip(String zipfile) throws IOException {
  //检查是否是zip文件,并判断文件是否存在
  checkFileName(zipfile);
  long startTime = System.currentTimeMillis();
  File zfile=new File(zipfile);
  //获取待解压文件的父路径
  String Parent=zfile.getParent()+"/";
  FileInputStream fis=new FileInputStream(zfile);
  Charset charset = Charset.forName("GBK");//默认UTF-8
// CheckedInputStream cis = new CheckedInputStream(fis,new CRC32());
  ZipInputStream zis = new ZipInputStream(fis,charset);// 输入源zip路径
  ZipEntry entry=null;
  BufferedOutputStream bos=null;
  while ((entry=zis.getNextEntry())!=null) {
    if (entry.isDirectory()) {
    File filePath=new File(Parent+entry.getName());
    //如果目录不存在,则创建
    if (!filePath.exists()) {
      filePath.mkdirs();
    }
    }else{
    FileOutputStream fos=new FileOutputStream(Parent+entry.getName());
    bos=new BufferedOutputStream(fos);
    byte buf[] = new byte[1024];
    int len;
    while ((len = zis.read(buf)) != -1) {
      bos.write(buf, 0, len);
    }
    zis.closeEntry();
    //关闭的时候会刷新
    bos.close();
    }
  }
  zis.close();
  long endTime = System.currentTimeMillis();
  System.out.println("解压完成!所需时间为:"+(endTime-startTime)+"ms");
// System.out.println("校验和:"+cis.getChecksum().getValue());
  }

  private void checkFileName(String name) {
  //文件是否存在
  if (!new File(name).exists()) {
    System.err.println("要解压的文件不存在!");
    System.exit(1);
  }
  // 判断是否是zip文件
  int index = name.lastIndexOf(".");
  String str=name.substring(index+1);
  if (!"zip".equalsIgnoreCase(str)) {
    System.err.println("不是zip文件,无法解压!");
    System.exit(1);
  } 
    }

Method 2:


Use zipFile to decompress. The method is similar to ZipInputStream. Entry is obtained continuously, and then Entry is used to judge. I heard that zipFile has a built-in buffer stream, so for the same The efficiency of decompressing a file multiple times is higher than ZipInputStream


 public void dozip(String zipfile) throws IOException {
  checkFileName(zipfile);
  long startTime = System.currentTimeMillis();
  // 获取待解压文件的父路径
  File zfile = new File(zipfile);
  String Parent = zfile.getParent() + "/";
  // 设置,默认是UTF-8
  Charset charset = Charset.forName("GBK");
  ZipFile zip = new ZipFile(zipfile, charset);
  ZipEntry entry = null;
  //封装解压后的路径
  BufferedOutputStream bos=null;
  //封装待解压文件路径
  BufferedInputStream bis=null;
  Enumeration<ZipEntry> enums = (Enumeration<ZipEntry>) zip.entries();
  while (enums.hasMoreElements()) {
    entry = enums.nextElement();
    if (entry.isDirectory()) {
    File filePath = new File(Parent + entry.getName());
    // 如果目录不存在,则创建
    if (!filePath.exists()) {
      filePath.mkdirs();
    }
    }else{
    bos=new BufferedOutputStream(new FileOutputStream(Parent + entry.getName()));
    //获取条目流
bis =new BufferedInputStream(zip.getInputStream(entry));
    byte buf[] = new byte[1024];
    int len;
    while ((len = bis.read(buf)) != -1) {
      bos.write(buf, 0, len);
    }

    bos.close();
    }
  }
  bis.close();
  zip.close();
  System.out.println("解压后的路径是:"+Parent);
  long endTime = System.currentTimeMillis();
  System.out.println("解压成功,所需时间为:"+(endTime-startTime)+"ms");
  }

  private void checkFileName(String name) {
  // 文件是否存在
  if (!new File(name).exists()) {
    System.err.println("要解压的文件不存在!");
    System.exit(1);
  }
  // 判断是否是zip文件
  int index = name.lastIndexOf(".");
  String str = name.substring(index + 1);
  if (!"zip".equalsIgnoreCase(str)) {
    System.err.println("不是zip文件,无法解压!");
    System.exit(1);
  }
  }

The above is the detailed content of Case study of decompressing and compressing folders in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

Java数据结构之AVL树详解Java数据结构之AVL树详解Jun 01, 2022 am 11:39 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use