压缩
package zip;
/**
* @ClassName---ZipUtil
* @Description TODO
* @Author MF
* @Data 2023/4/10 21:21
* @Version 1.0
**/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtil {
public static void main(String[] args) throws Exception {
File file = new File("./demo.txt");
String name = "demo.zip";
zipFile(file,name);
}
public static void zipFile(File sourceFile, String targetFileName) throws Exception {
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(targetFileName);
zos = new ZipOutputStream(fos);
ZipEntry entry = new ZipEntry(sourceFile.getName());
zos.putNextEntry(entry);
FileInputStream fis = new FileInputStream(sourceFile);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
fis.close();
} finally {
if (zos != null) {
zos.close();
}
if (fos != null) {
fos.close();
}
}
}
}
解压缩文件:
import java.io.File;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class UnzipUtil {
public static void unzipFile(String sourceFileName, String targetDirectory) throws Exception {
ZipFile zipFile = null;
try {
zipFile = new ZipFile(sourceFileName);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
byte[] buffer = new byte[1024];
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (entry.isDirectory()) {
continue;
}
File entryFile = new File(targetDirectory, entry.getName());
if (!entryFile.getParentFile().exists()) {
entryFile.getParentFile().mkdirs();
}
FileOutputStream fos = new FileOutputStream(entryFile);
try {
int len;
while ((len = zipFile.getInputStream(entry).read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
} finally {
fos.close();
}
}
} finally {
if (zipFile != null) {
zipFile.close();
}
}
}
}
使用时,可以通过调用ZipUtil.zipFile方法来进行压缩操作,也可以通过调用UnzipUtil.unzipFile方法来进行解压缩操作。