纯内存读取Zip文件

总结

方法1完全内存读取,只需要一个输入流即可;
方法2必须从操作系统本地读取文件才行,不能做到完全的内存读取;

方法1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public static void readZipFile0(InputStream in) throws Exception {
ZipInputStream zis = new ZipInputStream(in);
ZipEntry entry = null;
while ((entry = zis.getNextEntry()) != null) {
String entryName = entry.getName();
System.out.println(entryName);
int size = (int) entry.getSize();
byte[] buf = new byte[size];
if (entry.isDirectory()) {
//目录
continue;
}
byte[] bs = new byte[1024];
int len = 0;
int off = 0;
while ((len = zis.read(bs)) != -1) {
System.arraycopy(bs, 0, buf, off, len);
off += len;
}
FileOutputStream out = new FileOutputStream("D:/doc/"+entryName.replace("/", ""));
out.write(buf);
out.close();
}
zis.close();
}

方法2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public static void readZipFile1(String file) throws Exception {
ZipFile zf = new ZipFile(file);
InputStream in = new BufferedInputStream(new FileInputStream(file));
ZipInputStream zin = new ZipInputStream(in);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
if (ze.isDirectory()) {
//目录
continue;
}
System.out.println(ze.getName());
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
InputStream fileIn = zf.getInputStream(ze);
int val;
while((val=fileIn.read())!=-1) {
byteOut.write(val);
}
fileIn.close();
byteOut.writeTo(new FileOutputStream("D:/doc/"+ze.getName().replace("/", "")));
byteOut.close();
}
zin.closeEntry();
zin.close();
in.close();
zf.close();
}