需求:操作上传的zip文件,读取并上传每项文件(文件名称采用特定命名方式,便于保存)。
代码片段:
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 27 28 29 |
public void testUnzip() throws Exception{ String path = "C:\\demo.zip"; ZipFile zf = new ZipFile(path,Charset.forName("GB2312")); InputStream stream = new FileInputStream(new File(path)); ZipInputStream zipStream = new ZipInputStream(stream,Charset.forName("GB2312")); ZipEntry entry = null; File file = null; InputStream inputstream = null; FileOutputStream fos = null; int length; while(null != (entry = zipStream.getNextEntry())){ if (entry.isDirectory()) {} else { long size = entry.getSize(); if (size > 0) { inputstream=zf.getInputStream(entry); file = new File(path+"demo_"+entry.getName()); fos = new FileOutputStream(file); byte[] b = new byte[1024]; while((length = inputstream.read(b)) > -1){ fos.write(b,0,length); } fos.flush(); } } } fos.close(); inputstream.close(); zipStream.closeEntry(); } |