当前位置:网站首页>Zip compression decompression
Zip compression decompression
2022-06-12 21:33:00 【Besieged city_ city with high walls】
package com.jason.mrht.common.utils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/** * Zip Compress / Unzip tool class * Realize the compression of all files and empty directories under the target path and its sub paths * <p>Title: ZipUtil1</p> * <p>Description: </p> * @author fuxinbao * @date 2018 year 5 month 23 On the afternoon of Sunday 3:50:01 */
public class ZipUtils {
/** Buffer size */
private static final int BUFFER = 512;
/** * Get all files and empty subdirectories under the given source directory * Recursive implementation * @param srcFile * @return */
private static List<File> getAllFiles(File srcFile) {
List<File> fileList = new ArrayList<File>();
File[] tmp = srcFile.listFiles();
for (int i = 0; i < tmp.length; i++) {
if (tmp[i].isFile()) {
fileList.add(tmp[i]);
System.out.println("add file: "+tmp[i].getName());
}
if (tmp[i].isDirectory()) {
if (tmp[i].listFiles().length!=0){
// If it's not an empty directory , Then recursively add the directories and files under it
fileList.addAll(getAllFiles(tmp[i]));
}
else{
// If it's an empty directory , Add this directory to fileList
fileList.add(tmp[i]);
System.out.println("add empty dir: "+tmp[i].getName());
}
}
} // end for
return fileList;
}
/** * Take the relative path * Get the relative path of the file under the compressed source path according to the file name and compressed source path * * @param dirPath Compressed source path * @param file * * @return Relative paths */
private static String getRelativePath(String dirPath, File file) {
File dir = new File(dirPath);
String relativePath = file.getName();
while (true) {
file = file.getParentFile();
if (file == null) {
break;
}
if (file.equals(dir)) {
break;
} else {
relativePath = file.getName() + "/" + relativePath;
}
} // end while
return relativePath;
}
/** * create a file * According to the file name in the compressed package and the decompression destination path , Create the decompression target file , * Generate intermediate Directory * @param dstPath Decompression destination path * @param fileName File name in the compressed package * @return Unzip the target file * @throws IOException */
private static File createFile(String dstPath, String fileName) throws IOException {
String[] dirs = fileName.split("/");// Decompose all levels of directories of file names
File file = new File(dstPath);
if (dirs.length > 1) {
// The file has a parent directory
for (int i = 0; i < dirs.length - 1; i++) {
file = new File(file, dirs[i]);// Create file objects in turn and know the upper directory of the file
}
if (!file.exists()) {
file.mkdirs();// If the directory corresponding to the file does not exist , Create
System.out.println("mkdirs: " + file.getCanonicalPath());
}
file = new File(file, dirs[dirs.length - 1]);// create a file
return file;
} else {
if (!file.exists()) {
file.mkdirs();// If the directory of the target path does not exist , Create
System.out.println("mkdirs: " + file.getCanonicalPath());
}
file = new File(file, dirs[0]);// create a file
return file;
}
}
/** * Decompression method * * * @param zipFileName Compressed file name * @param dstPath Unzip the target path * * @return */
public static boolean unzip(String zipFileName, String dstPath) {
System.out.println("zip uncompressing...");
try {
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFileName));
ZipEntry zipEntry = null;
byte[] buffer = new byte[BUFFER];// Buffer
int readLength = 0;// The length of each reading
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
if (zipEntry.isDirectory()) {
// if zip Entry directory , You need to create this directory
File dir = new File(dstPath + "/" + zipEntry.getName());
if (!dir.exists()) {
dir.mkdirs();
System.out.println("mkdirs: " + dir.getCanonicalPath());
continue;// Jump out of
}
}
File file = createFile(dstPath, zipEntry.getName());// If it's a document , You need to create this file
System.out.println("file created: " + file.getCanonicalPath());
OutputStream outputStream = new FileOutputStream(file);
while ((readLength = zipInputStream.read(buffer, 0, BUFFER)) != -1) {
outputStream.write(buffer, 0, readLength);
}
outputStream.close();
System.out.println("file uncompressed: " + file.getCanonicalPath());
} // end while
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("unzip fail!");
return false;
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("unzip fail!");
return false;
}
System.out.println("unzip success!");
return true;
}
/** * Compression method * ( You can compress empty subdirectories ) * @param srcPath Compressed source path * @param zipFileName Target compressed file * * @return */
public static boolean zip(String srcPath, String zipFileName) {
System.out.println("zip compressing...");
File srcFile = new File(srcPath);
List<File> fileList = getAllFiles(srcFile);// All files to be compressed
byte[] buffer = new byte[BUFFER];// Buffer
ZipEntry zipEntry = null;
int readLength = 0;// The length of each reading
try {
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
for (File file : fileList) {
if (file.isFile()){
// If it's a document , Then compress the file
zipEntry = new ZipEntry(getRelativePath(srcPath, file));
zipEntry.setSize(file.length());
zipEntry.setTime(file.lastModified());
zipOutputStream.putNextEntry(zipEntry);
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
while ((readLength = inputStream.read(buffer, 0, BUFFER)) != -1) {
zipOutputStream.write(buffer, 0, readLength);
}
inputStream.close();
System.out.println("file compressed: " + file.getCanonicalPath());
}else {
// If it's a catalog ( Empty directory ) Then write this directory to zip entry
zipEntry = new ZipEntry(getRelativePath(srcPath, file)+"/");
zipOutputStream.putNextEntry(zipEntry);
System.out.println("dir compressed: " + file.getCanonicalPath()+"/");
}
} // end for
zipOutputStream.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("zip fail!");
return false;
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("zip fail!");
return false;
}
System.out.println("zip success!");
return true;
}
}
边栏推荐
- A high-value MySQL management tool
- SQL调优指南笔记17:Importing and Exporting Optimizer Statistics
- leetcode:210. 课程表 II
- Shell language
- atoi超强解析
- 数据批量写入
- SQL调优指南笔记18:Analyzing Statistics Using Optimizer Statistics Advisor
- 同花顺能开户吗,在APP上可以直接开通券商安全吗
- Teamwork collaboration application experience sharing | community essay solicitation
- 二分查找
猜你喜欢

Icml2022 | galaxy: active learning of polarization map

NPOI 创建Word
![Li Mu [practical machine learning] 1.4 data annotation](/img/e4/2593b1dec04476a9cc3b4af94dc189.jpg)
Li Mu [practical machine learning] 1.4 data annotation

Product Manager: "click here to jump to any page I want to jump" -- decoupling efficiency improving artifact "unified hop routing"

MySql主从复制

leetcode:210. 课程表 II

SQL调优指南笔记15:Controlling the Use of Optimizer Statistics

Introduction to the characteristics of balancer decentralized exchange market capitalization robot

结构体知识点all in

ASCII code comparison table
随机推荐
Binary search
Teambition 协作应用心得分享|社区征文
Risk control modeling X: Discussion on problems existing in traditional modeling methods and Exploration on improvement methods
Zip压缩解压缩
Allegro Xile technology, a developer of distributed cloud services, received millions of dollars of angel round financing and was independently invested by Yaotu capital
@loadbalance annotation of resttemplate
atoi超强解析
Pytoch distributed training error
#886 Possible Bipartition
How to design a message box through draftjs
Pytorch how to set random number seed to make the result repeatable
Mxnet record IO details
Fill in the checklist & lt; int&gt; Have default values? [repeat] - fill list & lt; int&gt; with default values? [duplicate]
有向图深拷贝
The service did not report any errors MySQL
Research Report on market supply and demand and strategy of China's hydraulic hammer industry
torch. nn. Linear() function
Introduction to the characteristics of balancer decentralized exchange market capitalization robot
递归调用知识点-包含例题求解二分查找、青蛙跳台阶、逆序输出、阶乘、斐波那契、汉诺塔。
Redis cluster mget optimization