Java直接读取zip文件有两种方法:
1. 通过zip文件的流直接读取文件
public static void readZipFile(ZipInputStream zipInputStream) throws IOException {
while((zipInputStream.getNextEntry())!=null){
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(zipInputStream));
String line;
while((line = bufferedReader.readLine())!= null){
System.out.println(line);
}
}
}
利用ZipInputStream流对象直接读取zip文件的各个文件内容,通过getNextEntry用来设置文件的读取位置,第一次get让文件操作指针跳转到第一个文件的读取入口,第二次get跳转到第二个文件的读取入口,以此类推。在实际项目进行zip读取操作时,如果只能获得压缩文件的流,可以通过这种方式读取压缩文件,否则就要绕远路了,这里要注意一下,文件名如果包含中文会抛异常。
2. 知道zip文件的存储位置直接读取zip文件
public static void readZipFile(String filePath) throws Exception {
java.util.zip.ZipFile zf = new java.util.zip.ZipFile(filePath);
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
ZipInputStream zin = new ZipInputStream(in);
ZipEntry ze;
while ((ze = zin.getNextEntry()) != null) {
long size = ze.getSize();
if (size > 0) {
BufferedReader br = new BufferedReader(
new InputStreamReader(zf.getInputStream(ze)));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
System.out.println();
}
zin.closeEntry();
}
直接读取已存储在硬盘上的zip文件,这种方式可以直接读取zip文件,当然也可以先解压再读取解压后的文件。