请用java写一个解压文件的代码
时间: 2024-05-08 22:22:25 浏览: 80
以下是一个基本的Java解压文件的示例代码:
```java
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 UnzipFileExample {
public static void main(String[] args) {
String zipFilePath = "path/to/zip/file.zip";
String destDirPath = "path/to/destination/folder";
unzipFile(zipFilePath, destDirPath);
}
public static void unzipFile(String zipFilePath, String destDirPath) {
try {
File destDir = new File(destDirPath);
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
String filePath = destDirPath + File.separator + entry.getName();
if (!entry.isDirectory()) {
extractFile(zipIn, filePath);
} else {
File dir = new File(filePath);
dir.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
System.out.println("File unzipped successfully!");
} 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)) > 0) {
fos.write(buffer, 0, bytesRead);
}
}
}
}
```
该代码将从指定的zip文件中提取所有文件并将其解压缩到指定的目录中。在这里,我们使用Java的ZipInputStream类来处理zip文件并使用Java的FileInputStream和FileOutputStream类来处理文件的读取和写入。
阅读全文