最近有个需求,要接受上穿的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”

 

posted on 2016-05-11 22:28  Flink菜鸟  阅读(1499)  评论(0编辑  收藏  举报