解压文件

由于项目需要,写了一段解压文件的测试。

package com.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

/**
 * 解压文件测试
 * @author 
 *
 */
public class test {
	
	public static void main (String[] args){
		//需要解压文件路径
		String zipPath = "D:/test.zip";
		//解压后存放文件的路径
		String descDir = "D:/test";
		try {
			ZipFile zip = new ZipFile(new File(zipPath));
			for(Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();){
				ZipEntry entry = entries.nextElement();
				String name = entry.getName();
				InputStream in = zip.getInputStream(entry);
				String outPath = (descDir+name).replace("\\*", "/");
				 // 解压后存放路径不存在,就创建
	            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));  
	            if (!file.exists()) {  
	                file.mkdirs();  
	            }
				FileOutputStream out = new FileOutputStream(outPath);
				byte[] b = new byte[1024];
				int i;
				while((i = in.read(b)) > 0){
					out.write(b, 0, i);
				}
				in.close();
				out.close();
			}
			zip.close();
		} catch (ZipException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

猜你喜欢

转载自my.oschina.net/u/3529861/blog/1609768
今日推荐