Java 截压缩包(zip包),解析xml文件-工具类
技术:在Java中,使用Java自带的java.util.zip.ZipFile包
代码示例如下:
注1:在下面的代码中,zipFilePath替换为要解压缩的.zip文件的实际路径,destDirectory替换为要解压到的目标目录的实际路径;接着运行unzip方法即可将.zip文件解压缩到目标目录。
注2:解压操作可能涉及到大量的文件和数据,建议在处理大型zip文件时使用适当的缓冲区大小,下面代码中使用了每次读取1024字节的缓冲区,可根据具体需要调整。
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;
/**
* <p>ClassName: UnzipUtil</p>
* <p>Description: zip包解压缩工具类</p>
* <p>Author: spring</p>
* <p>Date: 2024-06-12</p>
*/
public class UnzipUtil {
public static void main(String[] args) {
String zipFilePath = "/home/kone/test20240612.zip";
String destDirectory = "/home/kone/extracted";
unzip(zipFilePath, destDirectory);
}
public static void unzip(String zipFilePath, String destDirectory) {
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath))) {
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
String filePath = destDirectory + File.separator + entry.getName();
if (!entry.isDirectory()) {
extractFile(zipIn, filePath);
} else {
File dir = new File(filePath);
dir.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
System.out.println("Successfully extracted zip file.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
try (FileOutputStream fos = new FileOutputStream(filePath)){
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = zipIn.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
}
}