Java中的ZIP文件解压可以通过java.util.zip
包中的类来实现。以下是一个简单的示例代码,展示了如何解压一个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 UnzipUtility {
public static void unzip(String zipFilePath, String destDirectory) throws IOException {
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
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.mkdirs();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
}
private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[4096];
int read = 0;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}
public static void main(String[] args) {
String zipFilePath = "path/to/your/file.zip";
String destDirectory = "path/to/your/destination/directory";
try {
unzip(zipFilePath, destDirectory);
} catch (IOException e) {
e.printStackTrace();
}
}
}
ZipInputStream
的字符编码来解决。ZipInputStream
的字符编码来解决。希望这些信息对你有所帮助!如果有更多问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云