java实现解压zip文件并读取内容
时间: 2023-07-31 11:08:15 浏览: 375
你可以使用Java的java.util.zip包来实现解压zip文件并读取其内容。下面是一个示例代码:
```java
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
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 destinationFolder = "path/to/destination/folder";
try {
unzip(zipFilePath, destinationFolder);
readContents(destinationFolder);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void unzip(String zipFilePath, String destinationFolder) throws IOException {
byte[] buffer = new byte[1024];
File folder = new File(destinationFolder);
if (!folder.exists()) {
folder.mkdirs();
}
try (ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFilePath)))) {
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
String entryName = zipEntry.getName();
File entryFile = new File(destinationFolder + File.separator + entryName);
if (entryFile.getParentFile() != null && !entryFile.getParentFile().exists()) {
entryFile.getParentFile().mkdirs();
}
if (!zipEntry.isDirectory()) {
int bytesRead;
while ((bytesRead = zipInputStream.read(buffer)) != -1) {
entryFile.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(entryFile);
fileOutputStream.write(buffer, 0, bytesRead);
fileOutputStream.close();
}
} else {
entryFile.mkdirs();
}
zipInputStream.closeEntry();
}
}
}
public static void readContents(String folderPath) {
File folder = new File(folderPath);
if (folder.exists() && folder.isDirectory()) {
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
System.out.println("Directory: " + file.getName());
} else {
System.out.println("File: " + file.getName());
}
}
}
}
}
}
```
在上述示例代码中,你需要替换`zipFilePath`和`destinationFolder`变量的值为你实际的zip文件路径和解压后的目标文件夹路径。`unzip`方法负责解压zip文件,`readContents`方法用于读取解压后的文件夹内容并打印。
请确保你已经正确配置了Java环境,并导入了必要的类和包。运行示例代码后,它将解压zip文件并打印出解压后的文件和文件夹列表。
阅读全文