java 解压.zip
时间: 2024-05-09 16:12:00 浏览: 158
在Java中解压.zip文件可以使用java.util.zip包中的ZipInputStream类和ZipEntry来实现。下面是一个简单的示例代码:
```java
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipExample {
public static void main(String[] args) {
String zipFilePath = "path/to/your/file.zip";
String destDir = "path/to/destination/directory";
try {
File destDirectory = new File(destDir);
if (!destDirectory.exists()) {
destDirectory.mkdir();
}
FileInputStream fis = new FileInputStream(zipFilePath);
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
String entryName = zipEntry.getName();
String filePath = destDir + File.separator + entryName;
if (!zipEntry.isDirectory()) {
extractFile(zis, filePath);
} else {
File dir = new File(filePath);
dir.mkdir();
}
zis.closeEntry();
zipEntry = zis.getNextEntry();
}
zis.close();
fis.close();
System.out.println("解压完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
private static void extractFile(ZipInputStream zis, String filePath) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = zis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
}
}
```
你需要将上述代码中的"path/to/your/file.zip"替换为你要解压的.zip文件的路径,将"path/to/destination/directory"替换为你要将解压后的文件保存的目标目录路径。
阅读全文