java解压zip后读取文件内容
要解压zip文件并读取文件内容,可以使用Java的ZipInputStream类和BufferedReader类。
下面是一个示例代码,演示如何解压zip文件并读取文件内容:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipAndReadFileContent {
public static void main(String[] args) {
String zipFilePath = "path/to/your/zip/file.zip";
try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath))) {
ZipEntry entry = zipInputStream.getNextEntry();
while (entry != null) {
if (!entry.isDirectory()) {
System.out.println("File: " + entry.getName());
// 读取文件内容
BufferedReader reader = new BufferedReader(new InputStreamReader(zipInputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
zipInputStream.closeEntry();
entry = zipInputStream.getNextEntry();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的代码中,首先创建一个ZipInputStream对象来读取zip文件。然后使用getNextEntry()方法获取zip文件中的下一个条目(文件或目录)。如果当前条目是文件,我们使用BufferedReader类读取文件内容,并将其打印出来。最后,使用closeEntry()方法关闭当前条目,然后继续循环读取下一个条目,直到所有条目都被读取完毕。
请注意,上面的代码仅演示了如何读取zip文件中的文件内容。如果需要解压整个zip文件,请使用ZipOutputStream类和ZipEntry类来创建新的文件并将内容写入其中
原文地址: http://www.cveoy.top/t/topic/iimv 著作权归作者所有。请勿转载和采集!