您的位置:首页 > 编程语言 > Java开发

java压缩解压缩文件工具类的实现

2013-12-23 21:09 627 查看
下面代码有解释,直接创建类复制就可以用

package com.demo.zip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import android.util.Log;

/**
* Java utils 实现的Zip工具
*
* @author once
*/
public class ZipUtils {
private static final int BUFF_SIZE = 1024 * 1024; // 1M Byte

/**
* 批量压缩文件(夹)
*
* @param files
*            要压缩的文件(夹)列表
* @param zipFile
*            生成的压缩文件
* @throws IOException
*             当压缩过程出错时抛出
*/
public static void zipFiles(File[] files, File zipFile) throws IOException {
ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(
new FileOutputStream(zipFile), BUFF_SIZE));
for (File resFile : files) {
zipFile(resFile, zipout, "");
}
Log.i("info", "是否存在:" + zipFile.exists());
zipout.close();
}

/**
* 压缩文件
*
* @param resFile
*            需要压缩的文件(夹)
* @param zipout
*            压缩的目的文件
* @param rootpath
*            压缩的文件路径
* @throws FileNotFoundException
*             找不到文件时抛出
* @throws IOException
*             当压缩过程出错时抛出
*/
private static void zipFile(File resFile, ZipOutputStream zipout,
String rootpath) throws FileNotFoundException, IOException {
rootpath = rootpath
+ (rootpath.trim().length() == 0 ? "" : File.separator)
+ resFile.getName();
rootpath = new String(rootpath.getBytes("8859_1"), "GB2312");
if (resFile.isDirectory()) {
File[] fileList = resFile.listFiles();
for (File file : fileList) {
zipFile(file, zipout, rootpath);
}
} else {
byte buffer[] = new byte[BUFF_SIZE];
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(resFile), BUFF_SIZE);
zipout.putNextEntry(new ZipEntry(rootpath));
int realLength;
while ((realLength = in.read(buffer)) != -1) {
zipout.write(buffer, 0, realLength);
}
in.close();
zipout.flush();
zipout.closeEntry();
}
}

/**
* zip压缩功能测试. 将指定文件压缩后存到一压缩文件中
*
* @param baseDir
*            所要压缩的文件名
* @param objFileName
*            压缩后的文件名
* @return 压缩后文件的大小
* @throws Exception
*/
public static long createFileToZip(String zipFilename, String sourceFileName)
throws Exception {

File sourceFile = new File(sourceFileName);
byte[] buf = new byte[1024];

// 压缩文件名
File objFile = new File(zipFilename);
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFile));
ZipEntry ze = null;

// 创建一个ZipEntry,并设置Name和其它的一些属性
ze = new ZipEntry(sourceFile.getName());
ze.setSize(sourceFile.length());
ze.setTime(sourceFile.lastModified());

// 将ZipEntry加到zos中,再写入实际的文件内容
zos.putNextEntry(ze);
InputStream is = new BufferedInputStream(
new FileInputStream(sourceFile));
int readLen = -1;
while ((readLen = is.read(buf, 0, 1024)) != -1) {
zos.write(buf, 0, readLen);
}
is.close();
zos.close();
return objFile.length();
}

/* 删除文件 */
public static void delete(File file) {
if (file.exists() && file.isFile()) {
file.delete();
return;
}
if (file.isDirectory()) {
File[] childFiles = file.listFiles();
if (childFiles == null || childFiles.length == 0) {
// file.delete();
return;
}
for (int i = 0; i < childFiles.length; i++) {
delete(childFiles[i]);
}
// file.delete();
}
}

public static boolean deleteD(String sPath) {
// 如果sPath不以文件分隔符结尾,自动添加文件分隔符
if (!sPath.endsWith(File.separator)) {
sPath = sPath + File.separator;
}
File dirFile = new File(sPath);
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if (!dirFile.exists() || !dirFile.isDirectory()) {
return false;
}
boolean flag = true;
// 删除文件夹下的所有文件(包括子目录)
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
// 删除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag)
break;
} // 删除子目录
else {
flag = deleteD(files[i].getAbsolutePath());
if (!flag)
break;
}
}
if (!flag)
return false;
// 删除当前目录
return dirFile.delete();

}

public static boolean deleteFile(String sPath) {
boolean flag = false;
File file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}

/**
* 解压缩zip包
*
* @param zipFilePath
*            zip文件路径
* @param targetPath
*            解压缩到的位置,如果为null或空字符串则默认解压缩到跟zip包同目录跟zip包同名的文件夹下
* @throws IOException
*/
public static void unzip(String zipFilePath, String targetPath)
throws IOException {
OutputStream os = null;
InputStream is = null;
ZipFile zipFile = null;
try {
zipFile = new ZipFile(zipFilePath);
String directoryPath = "";
if (null == targetPath || "".equals(targetPath)) {
directoryPath = zipFilePath.substring(0,
zipFilePath.lastIndexOf("."));
} else {
directoryPath = targetPath;
}
@SuppressWarnings("rawtypes")
Enumeration entryEnum = zipFile.entries();
if (null != entryEnum) {
ZipEntry zipEntry = null;
while (entryEnum.hasMoreElements()) {
zipEntry = (ZipEntry) entryEnum.nextElement();
if (zipEntry.isDirectory()) {
directoryPath = directoryPath + File.separator
+ zipEntry.getName();
System.out.println(directoryPath);
continue;
}
if (zipEntry.getSize() > 0) {
// 文件
File targetFile = buildFile(directoryPath
+ File.separator + zipEntry.getName(), false);
os = new BufferedOutputStream(new FileOutputStream(
targetFile));
is = zipFile.getInputStream(zipEntry);
byte[] buffer = new byte[4096];
int readLen = 0;
while ((readLen = is.read(buffer, 0, 4096)) >= 0) {
os.write(buffer, 0, readLen);
}

os.flush();
os.close();
} else {
// 空目录
buildFile(
directoryPath + File.separator
+ zipEntry.getName(), true);
}
}
}
} catch (IOException ex) {
throw ex;
} finally {
if (null != zipFile) {
zipFile = null;
}
if (null != is) {
is.close();
}
if (null != os) {
os.close();
}
}
}

/**
*
* 生产文件 如果文件所在路径不存在则生成路径
*
*
*
* @param fileName
*
*            文件名 带路径
*
* @param isDirectory
*            是否为路径
*
* @return
*
* @author yayagepei
*
* @date 2008-8-27
*/

public static File buildFile(String fileName, boolean isDirectory) {

File target = new File(fileName);

if (isDirectory) {

target.mkdirs();

} else {

if (!target.getParentFile().exists()) {

target.getParentFile().mkdirs();

target = new File(target.getAbsolutePath());

}

}

return target;

}

/**
* 解压缩功能. 将zipFile文件解压到folderPath目录下.
*
* @throws Exception
*/
public synchronized static int upZipFile(File zipFile, String folderPath)
throws ZipException, IOException {
// public static void upZipFile() throws Exception{
ZipFile zfile = new ZipFile(zipFile);
@SuppressWarnings("rawtypes")
Enumeration zList = zfile.entries();
ZipEntry ze = null;
byte[] buf = new byte[1024];
while (zList.hasMoreElements()) {
ze = (ZipEntry) zList.nextElement();
if (ze.isDirectory()) {
Log.d("upZipFile", "ze.getName() = " + ze.getName());
String dirstr = folderPath + ze.getName();
// dirstr.trim();
dirstr = new String(dirstr.getBytes("8859_1"), "GB2312");
Log.d("upZipFile", "str = " + dirstr);
File f = new File(dirstr);
f.mkdir();
continue;
}
Log.d("upZipFile", "ze.getName() = " + ze.getName());
OutputStream os = new BufferedOutputStream(new FileOutputStream(
getRealFileName(folderPath, ze.getName())));
InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
while ((readLen = is.read(buf, 0, 1024)) != -1) {
os.write(buf, 0, readLen);
}
is.close();
os.close();
}
zfile.close();
return 0;
}

/**
* 给定根目录,返回一个相对路径所对应的实际文件名.
*
* @param baseDir
*            指定根目录
* @param absFileName
*            相对路径名,来自于ZipEntry中的name
* @return java.io.File 实际的文件
*/
public static File getRealFileName(String baseDir, String absFileName) {
String[] dirs = absFileName.split("/");
File ret = new File(baseDir);
String substr = null;
if (dirs.length > 1) {
for (int i = 0; i < dirs.length - 1; i++) {
substr = dirs[i];
try {
// substr.trim();
substr = new String(substr.getBytes("8859_1"), "GB2312");

} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ret = new File(ret, substr);

}
Log.d("upZipFile", "1ret = " + ret);
if (!ret.exists())
ret.mkdirs();
substr = dirs[dirs.length - 1];
try {
// substr.trim();
substr = new String(substr.getBytes("8859_1"), "GB2312");
Log.d("upZipFile", "substr = " + substr);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

ret = new File(ret, substr);
Log.d("upZipFile", "2ret = " + ret);
return ret;
}
return ret;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: