ZipFile和ZipInputSteam解压zip文件

最近有个需求,要接受上穿的zip文件,解压后读取里面的文件(应该还有目录),提前储备一下需要的知识。

贴在博客上,有需要的可以参考。

ZipInputStream解压文件:

@Test
public void test() {
String fileName = "/attach/01.zip";
String dest = "/attach/22";
try {
getFileInZip(fileName, dest);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

private void getFileInZip(String fileName, String dest) throws IOException {

File file = new File(fileName);
ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
OutputStream out = null;
ZipEntry zipEntry = null;
while ((zipEntry = zis.getNextEntry()) != null) {
File temp = new File(dest + File.separator + zipEntry.getName());
if (zipEntry.isDirectory()) {
temp.mkdirs();
continue;
}
System.out.println(zipEntry.getName() + "---" + zipEntry.getSize());
out = new FileOutputStream(temp);
int len = 0;
byte[] bytes = new byte[1024];
while ((len = zis.read(bytes)) != -1) {
out.write(bytes, 0, len);
}
out.close();
zis.closeEntry();
}
zis.close();
}

ZipFile解压文件:

 

@Test
public void test2() {
String fileName = "/attach/01.zip";
String dest = "/attach/22";
try {
testZipFile(fileName, dest);
} catch (ZipException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

 

private void testZipFile(String fileName, String dest) throws ZipException, IOException {
File file = new File(fileName);
ZipFile zipFile = new ZipFile(file);
Enumeration entries = zipFile.entries();
InputStream inputStream = null;
while (entries.hasMoreElements()) {

 

ZipEntry zipEntry = (ZipEntry) entries.nextElement();
File temp = new File(dest + File.separator + zipEntry.getName());
if (zipEntry.isDirectory()) {
temp.mkdirs();
continue;
}
inputStream = zipFile.getInputStream(zipEntry);

 

System.out.println(zipEntry.getName() + "---" + zipEntry.getSize());

 

if (!temp.getParentFile().exists()) {
temp.getParentFile().mkdirs();

 

}
FileOutputStream outputStream = new FileOutputStream(temp);
int len = 0;
byte bytes[] = new byte[1024];
while ((len = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
outputStream.close();
}

 

}

 

注:关于路径的说明,可能有的朋友会以为"/attach/01.zip”是linux或是unix里的路径,

  其实是windows里的路径(linux或unix里的路径就是这样的),我的eclipse是放在D盘的,

  使用"/attach/01.zip"会直接定位到“D:\\attach\\01.zip”

  windows的路径分隔符是 “\”,在java中是“\”是转义字符,所以需要写成"\\"

  linux的路径分隔符是 “/”,就不需要转义了

  当然在windows中使用相对路径时,是可以用“/”作为分隔符的,如:"/attach/01.zip”

 

转载于:https://www.cnblogs.com/Springmoon-venn/p/5483833.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值