ZIP是一种相当简单的分别压缩每个文件的存档格式。java中使用ZipFile、ZipInputStream快速读取或解压zip压缩包中的目录和文件。
完整示例:package com.weizhixi;
import org.apachemons.io.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
/**
* java 读取zip demo
*/
public class Test {
public static void main(String[] a) throws Exception {
File file = new File("C:\\Users\\XQ\\Desktop\\1.zip");
ZipFile zipFile = null;
ZipInputStream zin = null;
FileInputStream fis = null;
try {
Charset gbk = Charset.forName("GBK");
zipFile = new ZipFile(file, gbk);
fis = new FileInputStream(file);
zin = new ZipInputStream(fis, gbk);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
String path = ze.getName();
System.out.println(path);
if (!ze.isDirectory() && ze.toString().endsWith("txt")) {
InputStream inputStream = zipFile.getInputStream(ze);
List texts = IOUtils.readLines(inputStream);
for (String text : texts) {
System.out.println(" " + text);
}
inputStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (zin != null) {
zin.closeEntry();
zin.close();
}
if (fis != null)
fis.close();
if (zipFile != null)
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
测试:
测试zip压缩包如下图:
运行代码:测试/
测试/java/
测试/java/demo.txt
line1
line2
测试/php/
常见异常:
1、读取压缩包内文件的文件流时候,报空指针异常(即如无法获取demo.txt文件流)Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.(Reader.java:78)
at java.io.InputStreamReader.(InputStreamReader.java:113)
at org.apachemons.io.IOUtils.readLines(IOUtils.java:986)
at org.apachemons.io.IOUtils.readLines(IOUtils.java:968)
at com.weizhixi.Test.main(Test.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
这种错误是经常是由于编码问题导致。zipFile.getInputStream(ze)
zipFile 和 ze 都需要同样编码,如GBKCharset gbk = Charset.forName("GBK");
zipFile = new ZipFile(file, gbk);
zin = new ZipInputStream(fis, gbk);
2、使用完后记得关闭相关流。否则文件可能被占用。尤其zipFile.getInputStream(ze)
使用的工具类
我使用IOUtils读取文件,可按需要自定义。
maven:
commons-io
commons-io
2.4
原创文章,转载请注明出处:https://www.weizhixi/article/93.html
更多推荐
java zip 读取_java读取zip (含压缩包内的文件)
发布评论