/**
*
*/
package net.easipay.pepp.cbt.merchant.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/**
* @author Administrator
* Zip的解压缩文件,最好填写Parameter DirPath
*/
public class ZipUtil {
/**
* 默认的目录路径
*/
public static final String DEFAULT_DIR_PATH = "/";
public static final String DEFAULT_FILE_NAME = "/default.zip";
/**
* 解压zip文件
* @param is 输入流
* @param os 输出流
* @throws IOException
* @throws FileNotFoundException
*/
public static void unZip(InputStream is, String dirPath) throws FileNotFoundException, IOException{
if(null != is){
ZipInputStream zis = new ZipInputStream(is);
ZipEntry ze = null;
while((ze = zis.getNextEntry()) != null){
byte[] b = new byte[1024];
int j = 0;
String zipFileName = new String(ze.getName().getBytes(),Charset.forName("GBK"));
OutputStream os = new FileOutputStream(dirPath + zipFileName);
while((j = zis.read(b)) > 0){
os.write(b, 0, j);
}
os.close();
}
}
}
/**
* 压缩文件
* @param fs 多个文件
* @param zos 压缩文件流
* @return 压缩文件流
*/
public static ZipOutputStream zip(File f, ZipOutputStream zos,String parent){
try {
zos = null == zos ? new ZipOutputStream(new FileOutputStream(DEFAULT_FILE_NAME))
: zos;
parent = parent.length() == 0 ? "" : parent + "/";
if(f.isDirectory()){
File[] fs = f.listFiles();
for(File df : fs){
String fileName = new String(f.getName().getBytes(Charset.forName("GBK")));
zip(df,zos,parent + fileName);
}
} else {
String fileName = new String(f.getName().getBytes(Charset.forName("GBK")));
ZipEntry ze = new ZipEntry(parent + fileName);
zos.putNextEntry(ze);
InputStream is = new FileInputStream(f);
byte[] temp = new byte[1024];
int len = 0;
while((len = is.read(temp)) > 0){
zos.write(temp, 0, len);
}
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return zos;
}
public static void main(String[] args) {
File dirFile = new File("D:/ccc");
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new FileOutputStream("D:/ccc.zip"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
zos = ZipUtil.zip(dirFile, zos, "");
try {
zos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
另外我一直在寻求java解压缩rar的方法,但是查了资料说,rar是收费的所以java就没有支持他,不知道同仁们还有没有好的方式解决这样的需求,理论上是可以解决的。