参考:
http://www.cnblogs.com/lrh-xl/p/5509005.html
http://www.cnblogs.com/DreamDrive/p/5760477.html
package import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import javax.servlet.ServletContext; import org.springframework.web.multipart.MultipartFile; import com.google.common.collect.Maps; public class TestZipFile { public static void main(String[] args) { uploadInvoceFile(null,null); } /** * 解压页面上传的zip文件 * @param context * @param invoiceFile * @return */ static Map<String,Object> uploadInvoceFile(ServletContext context,MultipartFile multipartFile){ Map<String,Object> resultMap = Maps.newHashMap(); int sumOk = 0; int sumAll = 0; String savepath = DateUtils.getDate2Str("yyyy/MM/dd",new Date()); String basepath = context.getRealPath("/"); String path = basepath +"upload/invoice" + savepath+ "/"; String zipPath = path + multipartFile.getOriginalFilename(); //确保目录文件存在 File pathFile = new File(path); if(!pathFile.exists()){ pathFile.mkdirs(); } File zipTemp = new File(zipPath); ZipFile zipFile = null; try { multipartFile.transferTo(zipTemp); zipFile = new ZipFile(zipTemp); ZipInputStream zis = new ZipInputStream ( new FileInputStream(zipTemp) ) ; ZipEntry zipEntry = null ; byte[] bt = new byte[1024]; //遍历zip中的文件 while((zipEntry = zis.getNextEntry()) != null){ //System.out.println(zipEntry.getName());//3379_1234.jpg //System.out.println(zipEntry.getMethod());//8 //System.out.println(zipEntry.getSize());//-1 sumAll ++; //校验是否为订单号 String regex = "^[0-9]*$"; String orderId = zipEntry.getName().substring(0, zipEntry.getName().indexOf("_")); if(zipEntry.isDirectory() || StringUtils.isEmpty(orderId) || !orderId.matches(regex)){ continue; } String writecheckcode = zipEntry.getName().substring(zipEntry.getName().indexOf("_") + 1,zipEntry.getName().lastIndexOf(".")); File oneInvoice = new File(path + zipEntry.getName()); InputStream is = zipFile.getInputStream(zipEntry); OutputStream os = new FileOutputStream(oneInvoice) ; int len = 0; while((len = is.read(bt)) > 0){ os.write(bt,0,len); } os.close(); is.close(); //文件保存的相对路径 String shortPath = (path + zipEntry.getName()).replace(basepath, "/"); } zis.close(); zipFile.close(); } catch (IllegalStateException e) { e.printStackTrace(); resultMap.put("hasException",1); } catch (IOException e) { e.printStackTrace(); resultMap.put("hasException",1); } catch (Exception e) { e.printStackTrace(); resultMap.put("hasException",1); } finally{ //删除zipTemp zipTemp.delete(); resultMap.put("sumAll",sumAll); resultMap.put("sumOk",sumOk); resultMap.put("sumFail",sumAll - sumOk); } return resultMap; } }