兼容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 "";
}
/**
* 創(chuàng)建路徑
*
* @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;
// 得到該文件夾下的所有文件夾和文件數(shù)組
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,跳出循環(huán)
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");
}
}