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.
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!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor