帮我写一个解压并读取zip文件的java代码
时间: 2023-06-03 08:07:28 浏览: 112
好的,下面是对应的Java代码:
```
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipAndReadZipFile {
public static void main(String[] args) {
String zipFilePath = "path/to/zip/file.zip";
String outputFolder = "path/to/unzip/folder";
unzipAndRead(zipFilePath, outputFolder);
}
public static void unzipAndRead(String zipFilePath, String outputFolder) {
try {
File folder = new File(outputFolder);
if (!folder.exists()) {
folder.mkdir();
}
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry zipEntry = zipInputStream.getNextEntry();
while (zipEntry != null) {
String fileName = zipEntry.getName();
File newFile = new File(outputFolder + File.separator + fileName);
if (zipEntry.isDirectory()) {
newFile.mkdirs();
} else {
FileOutputStream fos = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int len;
while ((len = zipInputStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
zipEntry = zipInputStream.getNextEntry();
}
zipInputStream.closeEntry();
zipInputStream.close();
System.out.println("Unzipped and read the zip file successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个代码可以解压并读取指定的Zip文件,将其内容解压到指定的文件夹中。如果需要修改文件路径,可以将代码中的相应路径替换成实际的路径即可。
阅读全文