java解压zip
你可以使用Java的java.util.zip包来解压ZIP文件。
下面是一个简单的例子,展示如何使用Java解压ZIP文件:
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;
public class UnzipExample {
public static void main(String[] args) {
String zipFilePath = "path/to/your/zip/file.zip";
String destinationFolderPath = "path/to/destination/folder";
try {
unzip(zipFilePath, destinationFolderPath);
System.out.println("解压成功");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void unzip(String zipFilePath, String destinationFolderPath) throws IOException {
byte[] buffer = new byte[1024];
// 创建目标文件夹
File destinationFolder = new File(destinationFolderPath);
if (!destinationFolder.exists()) {
destinationFolder.mkdir();
}
// 创建ZipInputStream对象
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath));
// 获取ZipEntry对象并逐个解压
ZipEntry zipEntry = zipInputStream.getNextEntry();
while (zipEntry != null) {
String fileName = zipEntry.getName();
File newFile = new File(destinationFolderPath + File.separator + fileName);
// 创建父文件夹
new File(newFile.getParent()).mkdirs();
// 创建输出流
FileOutputStream fileOutputStream = new FileOutputStream(newFile);
// 读取并写入文件
int length;
while ((length = zipInputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, length);
}
// 关闭输出流
fileOutputStream.close();
// 关闭当前ZipEntry并获取下一个ZipEntry
zipInputStream.closeEntry();
zipEntry = zipInputStream.getNextEntry();
}
// 关闭ZipInputStream
zipInputStream.close();
}
}
你需要将zipFilePath替换为要解压的ZIP文件的路径,将destinationFolderPath替换为解压后文件的目标路径。
这个例子会将ZIP文件中的所有内容解压到指定的目标文件夹中
原文地址: http://www.cveoy.top/t/topic/iimn 著作权归作者所有。请勿转载和采集!