Home  >  Article  >  Java  >  Compression and decompression examples in java

Compression and decompression examples in java

零下一度
零下一度Original
2017-07-16 17:02:181548browse

During the development process, sometimes it is necessary to compress files to save hard disk space. So how to compress and decompress files using Java? It's very simple. Java provides us with a package that is responsible for compressing and decompressing files. That package is java.util.zip; (Note: This package has a very annoying point, the Chinese path will be garbled)

So how to solve this garbled code problem: Just use the ant.jar package of apache. The code will not change. If you write it with native JDK, then you only need to change the import package. Just like

1. Directory entry point

The directory entry point is the mapping of the file in the compressed file, representing the compressed file. When a file is compressed, a directory entry point is created and the file is written to that directory entry point. When decompressing, obtain the directory entry point and write the contents of the directory entry point to the specified file on the hard disk.

If the directory entry point is a folder, the name must end with a path separator. In the Windows operating system, the name separator is "/".

2. Automatic creation of files

Whether you call createNewFile() to create a file, or the output stream is responsible for creating it when creating an output stream files must ensure that the parent path already exists, otherwise the file cannot be created.

3. Directory creation

  • mkdirs(): Create a multi-level directory.

  • mkdir(): Create a first-level directory. If the parent path does not exist, the creation fails.

Second Compression

1. Create a directory entry point

First create a directory entry point for a file or folder. The name of the directory entry point is the path of the current file relative to the compressed file. The directory entry point name of the folder must end with a name separator to distinguish it from the file.


ZipEntry entry = new ZipEntry(压缩文件夹名称 + File.separator+文件或文件夹路径);

2. Write the directory entry point

Use the ZipOutputStream output stream to write the file to the corresponding In the directory entry point, writing is completed and the directory entry point is closed.

##3.Demo


package com.javase.io;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;import java.util.zip.ZipOutputStream;public class ZipUtils {    /**
     * 压缩一个文件夹
     * 
     * @throws IOException     */
    public void zipDirectory(String path) throws IOException {
        File file = new File(path);
        String parent = file.getParent();
        File zipFile = new File(parent, file.getName() + ".zip");
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
        zip(zos, file, file.getName());
        zos.flush();
        zos.close();
    }    /**
     * 
     * @param zos
     *            压缩输出流
     * @param file
     *            当前需要压缩的文件
     * @param path
     *            当前文件相对于压缩文件夹的路径
     * @throws IOException     */
    private void zip(ZipOutputStream zos, File file, String path) throws IOException {        // 首先判断是文件,还是文件夹,文件直接写入目录进入点,文件夹则遍历
        if (file.isDirectory()) {
            ZipEntry entry = new ZipEntry(path + File.separator);// 文件夹的目录进入点必须以名称分隔符结尾            zos.putNextEntry(entry);
            File[] files = file.listFiles();            for (File x : files) {
                zip(zos, x, path + File.separator + x.getName());
            }
        } else {
            FileInputStream fis = new FileInputStream(file);// 目录进入点的名字是文件在压缩文件中的路径
            ZipEntry entry = new ZipEntry(path);
            zos.putNextEntry(entry);// 建立一个目录进入点

            int len = 0;            byte[] buf = new byte[1024];            while ((len = fis.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            zos.flush();
            fis.close();
            zos.closeEntry();// 关闭当前目录进入点,将输入流移动下一个目录进入点        }
    }}

Three decompressed files

1. Basic idea

When decompressing a file, first obtain the directory entry point in the compressed file, and based on the directory The entry point creates a file object and writes the contents of the directory entry point to the hard disk file.

#2.Demo

package com.javase.io;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;import java.util.zip.ZipOutputStream;public class ZipUtils {private String basePath;    /**
     * 解压文件
     * 
     * @param unzip
     * @throws IOException     */
    public void unzip(String unzip) throws IOException {
        File file = new File(unzip);
        basePath = file.getParent();
        FileInputStream fis = new FileInputStream(file);
        ZipInputStream zis = new ZipInputStream(fis);
        unzip(zis);
    }    private void unzip(ZipInputStream zis) throws IOException {
        ZipEntry entry = zis.getNextEntry();        if (entry != null) {
            File file = new File(basePath + File.separator + entry.getName());            if (file.isDirectory()) {                // 可能存在空文件夹
                if (!file.exists())
                    file.mkdirs();
                unzip(zis);
            } else {
                File parentFile = file.getParentFile();                if (parentFile != null && !parentFile.exists())
                    parentFile.mkdirs();
                FileOutputStream fos = new FileOutputStream(file);// 输出流创建文件时必须保证父路径存在
                int len = 0;                byte[] buf = new byte[1024];                while ((len = zis.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.flush();
                fos.close();
                zis.closeEntry();
                unzip(zis);
            }
        }
    }

}

The above is the detailed content of Compression and decompression examples 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