解压zip,获得里面的文件列表

/**
	 * unZip解压文件
	 * @param file_zip 目标文件
	 * @param descDir 解压文件存放目录
	 * @param urlList 解压后的文件列表 
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public boolean unZip(File file_zip, String descDir,  List<String> urlList) {
	    boolean flag = false;
	    File pathFile = new File(descDir);
	    if(!pathFile.exists()){
	        pathFile.mkdirs();
	    }
	    InputStream in= null ;
	    OutputStream out = null;
	    ZipFile zip = null;
	    try {
	        
	        zip = new ZipFile(file_zip, Charset.forName("gbk"));//指定编码,否则压缩包里面不能有中文目录
	        for(Enumeration entries = zip.entries(); entries.hasMoreElements();){
	            ZipEntry entry = (ZipEntry)entries.nextElement();
	            String zipEntryName = entry.getName();
	            in = zip.getInputStream(entry);
	            String outPath = (descDir+zipEntryName).replace("/", File.separator);
	            //判断路径是否存在,不存在则创建文件路径
	            File file = new File(outPath.substring(0, outPath.lastIndexOf(File.separator)));
	            if(!file.exists()){
	                file.mkdirs();
	            }
	            //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
	            if(new File(outPath).isDirectory()){
	                continue;
	            }
	            //保存文件路径信息
	            urlList.add(outPath);

	            out = new FileOutputStream(outPath);
	            byte[] buf1 = new byte[2048];
	            int len;
	            while((len=in.read(buf1))>0){
	                out.write(buf1,0,len);
	            }
	        }
	        flag = true;
	        
	    } catch (IOException e) {
	        e.printStackTrace();
	    }finally {
			try {
				if(null != in) {
					in.close();
				}
				if(null != out) {
					out.close();
				}
				if(null != zip) {
					zip.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	    return flag;
	}
	
	@Test
	public void test1() {
		
		String zipPath = "D://20190104150639.zip"; // 文件位置
		File zipFile = new File(zipPath );
		
		String descDir = "D:"; // 文件解压后的路径 
		
		List<String> urlList = new ArrayList<>(); // 文件列表
		unZip(zipFile, descDir, urlList);
		System.err.println(urlList);
	}

猜你喜欢

转载自blog.csdn.net/qq_41750093/article/details/86136840