解压Zip文件的工具类
2017-05-16 本文已影响100人
靈08_1024
兼容JDK7下的java自带解压和Apache的解压。
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.channels.FileChannel;
import java.util.Enumeration;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
public class FileOperatorHelper {
/**
* 解压缩
* 以好压 压缩工具的压缩包(Java自带解压)
* @param zipFile
* @param decompressPath
* @throws IOException
*/
public static void unzipFile(String zipFile, String decompressPath)
throws IOException {
int BUFFER = 4096;
String zename = null;
InputStream is = null;
try {
File dir = new File(decompressPath);
java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFile);
Enumeration enumer = zf.entries();
while (enumer.hasMoreElements()) {
java.util.zip.ZipEntry ze = (java.util.zip.ZipEntry) enumer.nextElement();
zename = ze.getName();
// 文件名,不支持中文.
if (zename == ""
|| zename.compareTo("\\") == 0
// 当解压文件中有文件夹时,解压失败,ZF无法关闭,导致对压缩文件无法操作
|| zename.compareTo("/") == 0
|| zename.substring(zename.length() - 1,
zename.length()).equals("/")
|| zename.substring(zename.length() - 1,
zename.length()).equals("\\")) {
continue;
}
File file = new File(dir.getAbsolutePath() + File.separator
+ zename).getParentFile();
if (!file.exists()) {
file.mkdirs();
}
int num;
is= new BufferedInputStream(zf.getInputStream(ze));
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(decompressPath.concat(zename)));
byte[] buf = new byte[BUFFER];
while ((num = is.read(buf, 0, BUFFER)) != -1) {
out.write(buf, 0, num);
}
is.close();
out.close();
}
zf.close();
} catch (Exception e) {
if ("MALFORMED".equals(e.getMessage())) {
unzipFileWinZip(zipFile, decompressPath);
} else {
throw new IllegalArgumentException("解压缩异常", e);
}
}
}
/**
* 2016年12月30日16:08:15 wx 新增
* 自己给自己挖了一个坑。不要向客户推荐软件。
* 推荐的多,兼容的多。子子孙孙无穷尽也。
* 以winZip或者360压缩工具的压缩包。谨记!以Apache解压
*/
public static void unzipFileWinZip(String zipFile, String decompressPath)
throws IOException {
int BUFFER = 4096;
String zename = null;
InputStream is = null;
try {
File dir = new File(decompressPath);
ZipFile zf = new ZipFile(zipFile);
Enumeration enumer = zf.getEntries();
while (enumer.hasMoreElements()) {
ZipEntry ze = (ZipEntry) enumer.nextElement();
zename = ze.getName();
// 文件名,不支持中文.
if (zename == ""
|| zename.compareTo("\\") == 0
// 当解压文件中有文件夹时,解压失败,ZF无法关闭,导致对压缩文件无法操作
|| zename.compareTo("/") == 0
|| zename.substring(zename.length() - 1,
zename.length()).equals("/")
|| zename.substring(zename.length() - 1,
zename.length()).equals("\\")) {
continue;
}
File file = new File(dir.getAbsolutePath() + File.separator
+ zename).getParentFile();
if (!file.exists()) {
file.mkdirs();
}
int num;
is= new BufferedInputStream(zf.getInputStream(ze));
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(decompressPath.concat(zename)));
byte[] buf = new byte[BUFFER];
while ((num = is.read(buf, 0, BUFFER)) != -1) {
out.write(buf, 0, num);
}
is.close();
out.close();
}
zf.close();
} catch (Exception e) {
throw new IllegalArgumentException("解压缩异常", e);
}
}
public static void deltree(File directory) {
if (directory.exists() && directory.isDirectory()) {
File[] fileArray = directory.listFiles();
for (int i = 0; i < fileArray.length; i++) {
if (fileArray[i].isDirectory()) {
deltree(fileArray[i]);
} else {
fileArray[i].delete();
}
}
directory.delete();
}
}
public static void deltree(String filepath) {
File file = new File(filepath);
deltree(file);
}
public static void copyFile(String sourceFileName,
String destinationFileName) {
copyFile(new File(sourceFileName), new File(destinationFileName));
}
public static void copyFile(File source, File destination) {
if (!source.exists()) {
return;
}
if ((destination.getParentFile() != null)
&& (!destination.getParentFile().exists())) {
destination.getParentFile().mkdirs();
}
try {
FileChannel srcChannel = new FileInputStream(source).getChannel();
FileChannel dstChannel = new FileOutputStream(destination)
.getChannel();
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
srcChannel.close();
dstChannel.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public static void copyFile(FileChannel source, File destination) {
if (source == null) {
return;
}
if ((destination.getParentFile() != null)
&& (!destination.getParentFile().exists())) {
destination.getParentFile().mkdirs();
}
try {
FileChannel dstChannel = new FileOutputStream(destination)
.getChannel();
dstChannel.transferFrom(source, 0, source.size());
dstChannel.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* 目录对拷
*
* @param sourcepath
* @param destpath
*/
public static void copyPath(String sourcepath, String destpath) {
File sf = new File(sourcepath);
if (!sf.exists() || sf.isFile()) {
return;
}
File df = new File(destpath);
if (!df.exists()) {
try {
makedirs(destpath);
} catch (Exception e) {
e.printStackTrace();
}
}
File[] fs = sf.listFiles();
if (fs != null) {
for (int i = 0; i < fs.length; i++) {
File tf1 = fs[i];
File tf2 = new File(destpath + File.separator + tf1.getName());
copyFile(tf1, tf2);
}
}
}
/**
* 压缩多个文件
*
* @param zipfile
* @param file
* @throws Exception
*/
public static void zip(String zipfile, String[] file) throws Exception {
FileOutputStream f = new FileOutputStream(zipfile);
ZipOutputStream out = new ZipOutputStream(new DataOutputStream(f));
for (int i = 0; i < file.length; i++) {
FileInputStream stream = new FileInputStream(file[i]);
DataInputStream in = new DataInputStream(stream);
out.putNextEntry(new ZipEntry(getFileName(file[i])));
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
in.close();
}
out.close();
}
public static void zip2(String zipfile, String[] file) throws Exception {
FileOutputStream f = new FileOutputStream(zipfile);
ZipOutputStream out = new ZipOutputStream(new DataOutputStream(f));
for (int i = 0; i < file.length; i++) {
String string = file[i];
string.replaceAll("\\", "\\\\\\\\");
FileInputStream stream = new FileInputStream(string);
DataInputStream in = new DataInputStream(stream);
out.putNextEntry(new ZipEntry(getFileName(file[i])));
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
in.close();
}
out.close();
}
/**
* 压缩指定文件夹中文件
*
* @param zipfile
* 压缩后完整名称
* @param inputFolder
* 输入文件夹
* @throws Exception
* 异常
*/
public static void zip(String zipfile, String inputFolder) throws Exception {
File d = new File(inputFolder);
String[] refiles = d.list();
String[] files = new String[refiles.length];
for (int i = 0; i < files.length; i++) {
files[i] = inputFolder + System.getProperty("file.separator")
+ refiles[i];
}
zip(zipfile, files);
}
/**
* 替换文件名称中分隔符
*
* @param filepath
* @return
*/
public static String formatpath(String filepath) {
String file = StringUtils.replace(filepath, "/",
System.getProperty("file.separator"));
file = StringUtils.replace(file, "\\",
System.getProperty("file.separator"));
return file;
}
/**
* 得到文件名称(带扩展名)
*
* @param selectedFile
* @return
*/
public static String getFileName(String selectedFile) {
String s = formatpath(selectedFile);
int pos = s.lastIndexOf(System.getProperty("file.separator"));
if (pos > 0) {
return s.substring(pos + 1);
}
return s;
}
/**
* @param selectedFile
* 文件完整路径
* @return 盘符:\文件夹
*/
public static String getFilePath(String selectedFile) {
String s = formatpath(selectedFile);
int pos = s.lastIndexOf(System.getProperty("file.separator"));
if (pos > 0) {
return s.substring(0, pos);
}
return "";
}
/**
* 创建路径
*
* @param filename
* @return
* @throws ServiceException
*/
public static String makedirs(String filename) throws Exception {
log.info("creating file name == " + filename);
File f = new File(filename);
if (f.exists()) {
log.info("creating file does exist");
if (f.isFile()) {
f.delete();
} else {
return filename;
}
}
f.mkdirs();
return filename;
}
/**
* @param delFolder
* 要删除的文件夹
* @return boolean
*/
public static boolean deleteFolder(File delFolder) {
if (delFolder == null || !delFolder.exists()) {
return false;
}
// 目录是否已删除
boolean hasDeleted = true;
// 得到该文件夹下的所有文件夹和文件数组
File[] allFiles = delFolder.listFiles();
for (int i = 0; i < allFiles.length; i++) {
// 为true时操作
if (hasDeleted) {
if (allFiles[i].isDirectory()) {
// 如果为文件夹,则递归调用删除文件夹的方法
hasDeleted = deleteFolder(allFiles[i]);
} else if (allFiles[i].isFile()) {
// 删除文件
try {
if (!allFiles[i].delete()) {
// 删除失败,返回false
hasDeleted = false;
}
} catch (Exception e) {
// 异常,返回false
hasDeleted = false;
}
}
} else {
// 为false,跳出循环
break;
}
}
if (hasDeleted) {
// 该文件夹已为空文件夹,删除它
delFolder.delete();
}
return hasDeleted;
}
/**
* @param str
* 中文字符串
* @return String
*/
public static String make8859toGB(String str) {
try {
String str8859 = new String(str.getBytes("8859_1"), "GB2312");
return str8859;
} catch (UnsupportedEncodingException ioe) {
return str;
}
}
/**
* 解压缩
*
* @param zipfile
* 压缩文件名
* @param dirname
* 文件路径
*/
public static void extract(String zipfile, String dirname) throws Exception {
try {
File newdir = new File(dirname);
if (newdir.exists()) {
deleteFolder(newdir);
}
newdir.mkdir();
File infile = new File(zipfile);
// 检查是否是ZIP文件
ZipFile zip = new ZipFile(infile);
zip.close();
// 建立与目标文件的输入连接
ZipInputStream in = new ZipInputStream(new FileInputStream(infile));
java.util.zip.ZipEntry file = in.getNextEntry();
int i;
byte[] c = new byte[1024];
int slen;
while (file != null) {
i = make8859toGB(formatpath(file.getName())).lastIndexOf(
System.getProperty("file.separator"));
if (i != -1) {
File dirs = new File(dirname
+ File.separator
+ make8859toGB(formatpath(file.getName()))
.substring(0, i));
dirs.mkdirs();
dirs = null;
}
if (file.isDirectory()) {
File dirs = new File(
make8859toGB(formatpath(file.getName())));
dirs.mkdir();
dirs = null;
} else {
FileOutputStream out = new FileOutputStream(dirname
+ File.separator
+ make8859toGB(formatpath(file.getName())));
while ((slen = in.read(c, 0, c.length)) != -1) {
out.write(c, 0, slen);
}
out.close();
}
file = in.getNextEntry();
}
in.close();
} catch (ZipException zipe) {
throw new Exception("不是一个ZIP文件!文件格式错误." + zipe.getMessage());
} catch (IOException ioe) {
throw new Exception("文件读取错误." + ioe.getMessage());
} catch (Exception e) {
throw new Exception("其他错误." + e.getMessage());
}
}
/**
* 删除文件或者文件夹
*
* @param filepathname
* @throws IOException
*/
public static void deleteFile(String filepathname) throws IOException {
log.info("deleting filename == " + filepathname);
File file = new File(filepathname);
if (file.exists()) {
log.info("file exist");
if (file.isFile()) {
log.info("is file");
file.delete();
} else {
log.info("is Directory");
File[] files = file.listFiles();
while (files != null && files.length > 0) {
if (files[0] != null && files[0].exists()) {
if (files[0].isFile()) {
files[0].delete();
} else {
deleteFile(files[0].getPath());
}
files = file.listFiles();
}
}
file.delete();
}
}
log.info("deleting file does not exist");
}
}