java 解压缩文件
因为是第三方平台,解决中文乱码问题,所以需要下载 ant.jar 包,直接百度下载即可
package cn.com.decompression;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipException;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
/**
* 解压文件,可以处理中文文件。(测试类是: cn.com.test.UnZip2)
*/
public class Decompression {
private static final int buffer = 2048;
private static File file = null;
private static InputStream is = null;
private static FileOutputStream fos = null;
private static BufferedOutputStream bos = null;
private static ZipFile zipFile = null;
/*
* 解压缩文件
*/
public static void unZip(String path) {
int count = -1;
int index = -1;
String savepath = "";
// boolean flag = false;
//存储路径-》文件存放的当前路径
savepath = path.substring(0, path.lastIndexOf("\\")) + "\\";
try {
// 文件路径
zipFile = new ZipFile(path,"GBK");//设置解压编码是 gbk,用来处理winRAR压缩的文件。
//枚举
Enumeration<?> entries = zipFile.getEntries();
//遍历
while (entries.hasMoreElements()) {
byte buf[] = new byte[buffer];
// 得到实体
ZipEntry entry = (ZipEntry) entries.nextElement();
// 文件名称
String filename = entry.getName();
index = filename.lastIndexOf("/");
if (index > -1)
filename = filename.substring(index + 1);
filename = savepath + filename;
//判断是不是图片
// flag = isPics(filename);
// if(!flag)
// continue;
//
file = new File(filename);
file.createNewFile();
is = zipFile.getInputStream(entry);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, buffer);
while ((count = is.read(buf, 0, buffer)) > -1) {
bos.write(buf, 0, count);
}
bos.flush();
}
System.out.println("目标文件是压缩文件,已解压到目标地址");
} catch (ZipException e) {
System.err.println("压缩文件内容为空,无法解压");
}catch (IOException e) {
System.err.println("文件解压中出现未知的错误");
}
finally{
try {
if (bos != null)
bos.close();
if (fos != null)
fos.close();
if (is != null)
is.close();
if (zipFile != null)
zipFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/*
* 判断是不是 图片
*/
public static boolean isPics(String filename) {
boolean flag = false;
if (filename.endsWith(".jpg") || filename.endsWith(".gif")
|| filename.endsWith(".bmp") || filename.endsWith(".png"))
flag = true;
return flag;
}
}