当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢
随机推荐
How to design a message box through draftjs
#141 Linked List Cycle
Composer version degradation
Turing prize winner: what should I pay attention to if I want to succeed in my academic career?
Insert sort
RestTemplate的@LoadBalance注解
同花顺能开户吗,在APP上可以直接开通券商安全吗
Pytorch how to set random number seed to make the result repeatable
ASCII 码对照表
ORM implements the mapping relationship between classes and tables, class attributes and fields
torch. nn. Linear() function
Gather function in pytorch_
jsonUtils
Draw according to weight
插入排序
在同花顺开户安全么,买股票怎么网上开户
#886 Possible Bipartition
Teambition 协作应用心得分享|社区征文
Semester summary of freshman year
ASCII code comparison table