支持中文ZIP解压,压缩

支持中文ZIP解压,压缩
写道
package com.dragon.android.pandaspace.util.code;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
* Description: zip管理器
*
* @version 1.0.0
*/
public class ZipManager {

static final int BUFFER = 8192;

/**
* zip压缩功能测试. 将d:\\temp\\zipout目录下的所有文件连同子目录压缩到d:\\temp\\out.zip.
*
* @param baseDir
* 所要压缩的目录名(包含绝对路径)
* @param objFileName
* 压缩后的文件名
* @throws Exception
*/
public static void createZip(String baseDir, String objFileName) throws Exception {
File folderObject = new File(baseDir);

if (folderObject.exists()) {
List<File> fileList = getSubFiles(new File(baseDir));

// 压缩文件名
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFileName));

ZipEntry ze = null;
byte[] buf = new byte[1024];
int readLen = 0;
for (int i = 0; i < fileList.size(); i++) {
File f = (File) fileList.get(i);
System.out.println("Adding: " + f.getPath() + f.getName());

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

// 将ZipEntry加到zos中,再写入实际的文件内容
zos.putNextEntry(ze);
InputStream is = new BufferedInputStream(new FileInputStream(f));
while ((readLen = is.read(buf, 0, 1024)) != -1) {
zos.write(buf, 0, readLen);
}
is.close();
}
zos.close();
} else {
throw new Exception("this folder isnot exist!");
}
}

/**
* 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();
}

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

byte[] buf = new byte[1024];

// 压缩文件名
File objFile = zipFile;

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();
}

/**
* 测试解压缩功能. 将d:\\download\\test.zip连同子目录解压到d:\\temp\\zipout目录下。
* @param sourceZip
* @param outFileName
* @param suffix 只解压 后缀为suffix文件
* @throws IOException
*/
public static void releaseZipToFile(String sourceZip, String outFileName,String suffix) throws IOException {
ZipFile zfile = new ZipFile(sourceZip);
Enumeration zList = zfile.entries();
ZipEntry ze = null;
byte[] buf = new byte[1024 * 8];
while (zList.hasMoreElements()) {
// 从ZipFile中得到一个ZipEntry
ze = (ZipEntry) zList.nextElement();
if (ze.isDirectory()) {
continue;
}
if(suffix!=null){
String name=ze.getName();
if(!name.endsWith(suffix)){
continue;
}
}
// 以ZipEntry为参数得到一个InputStream,并写到OutputStream中
OutputStream os = null;
os = new BufferedOutputStream(new FileOutputStream(getRealFileName(outFileName, ze.getName())));
InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
while ((readLen = is.read(buf, 0, 1024 * 8)) != -1) {
os.write(buf, 0, readLen);
}
is.close();
os.close();
// //Log.i("ZipManager", "[releaseZipToFile]"+"Extracted: " +
// ze.getName());
}
zfile.close();
}

public static void releaseZipToFile(String sourceZip, String outFileName) throws IOException {
releaseZipToFile(sourceZip,outFileName,null);
}

public static File releaseFileFromZip(String sourceZip,String outFilePath,String fileName) throws IOException{
byte[] buf = new byte[1024 * 8];
ZipFile zfile = new ZipFile(sourceZip);
ZipEntry ze=zfile.getEntry(fileName);
File destFile = null;
if(ze!=null){
OutputStream os = null;
destFile = getRealFileName(outFilePath, ze.getName());
os = new BufferedOutputStream(new FileOutputStream(destFile));
InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
while ((readLen = is.read(buf, 0, 1024 * 8)) != -1) {
os.write(buf, 0, readLen);
}
is.close();
os.close();
}
zfile.close();
return destFile;
}

public static void releaseFileFromZip(String sourceZip, String sourceEntryName, String destDir, String destFileName) throws IOException{
byte[] buf = new byte[1024 * 8];
ZipFile zfile = new ZipFile(sourceZip);
ZipEntry ze=zfile.getEntry(sourceEntryName);
if(ze!=null){//文件的情况
OutputStream os = null;
InputStream is = null;
try {
os = new BufferedOutputStream(new FileOutputStream(getRealFileName(destDir, destFileName)));
is = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
while ((readLen = is.read(buf, 0, 1024 * 8)) != -1) {
os.write(buf, 0, readLen);
}
} finally {
if(is != null) {
is.close();
is = null;
}
if(os != null) {
os.close();
os = null;
}

}
} else {//有文件夹的情况
Enumeration<ZipEntry> n = (Enumeration<ZipEntry>) zfile.entries();
while(n.hasMoreElements()) {
ZipEntry zipFile = n.nextElement();
if(zipFile!=null){
String entryname = zipFile.getName();
if(entryname.startsWith(sourceEntryName)) {
String endPath = entryname.substring(sourceEntryName.length());
if(endPath.endsWith("/")) {//文件夹
File file = new File(destDir + destFileName + endPath);
if(!file.exists()) {
file.mkdirs();
}
} else {//文件
OutputStream os = null;
InputStream is = null;
try {
os = new BufferedOutputStream(new FileOutputStream(getRealFileName(destDir + destFileName, endPath)));
is = new BufferedInputStream(zfile.getInputStream(zipFile));
int readLen = 0;
while ((readLen = is.read(buf, 0, 1024 * 8)) != -1) {
os.write(buf, 0, readLen);
}
} finally {
if(is != null) {
is.close();
is = null;
}
if(os != null) {
os.close();
os = null;
}

}
}
}
}
}
}
zfile.close();
}
/**
* 解压ZIP包, 保留目录结构。
* @throws IOException
*/
public static ArrayList<Object> ectract(String sZipPathFile, String sDestPath, boolean autoRename,boolean isStop) throws IOException {
ArrayList<Object> allFileName = new ArrayList<Object>();
// 先指定压缩档的位置和档名,建立FileInputStream对象
FileInputStream fins = new FileInputStream(sZipPathFile);
// 将fins传入ZipInputStream中
ZipInputStream zins = new ZipInputStream(fins);
ZipEntry ze = null;
byte ch[] = new byte[BUFFER];
while ((ze = zins.getNextEntry()) != null) {
if (isStop) {
return null;
}
String name = ze.getName();
name = name.replace('\\', '/');
name = name.replaceAll("\\s", "%20");
File zfile = new File(sDestPath + name);
File fpath = new File(zfile.getParentFile().getPath());
if (ze.isDirectory()) {
if (!zfile.exists())
zfile.mkdirs();
zins.closeEntry();
} else {
if (!fpath.exists())
fpath.mkdirs();
FileOutputStream fouts = new FileOutputStream(zfile);
int i;
allFileName.add(zfile.getAbsolutePath());
while ((i = zins.read(ch,0,BUFFER)) != -1)
fouts.write(ch, 0, i);
zins.closeEntry();
fouts.close();
}
}
fins.close();
zins.close();
return allFileName;
}
// /**
// * 测试解压缩功能. 将d:\\download\\test.zip连同子目录解压到d:\\temp\\zipout目录下.
// *
// * @throws Exception
// */
// @SuppressWarnings("unchecked")
// public static void releaseDecodeZipToFile(String sourceZip, String
// outFileName, String password) throws Exception {
// SecretKeySpec dks = new SecretKeySpec(password.getBytes(), "AES");
// SecureRandom sr = new SecureRandom();
// Cipher ciphers = Cipher.getInstance("AES/CBC/PKCS5Padding");
// IvParameterSpec spec = new IvParameterSpec(dks.getEncoded());
// ciphers.init(Cipher.DECRYPT_MODE, dks, spec, sr);
//
// ZipFile zfile = new ZipFile(sourceZip);
// System.out.println(zfile.getName());
// Enumeration zList = zfile.entries();
// ZipEntry ze = null;
// byte[] buf = new byte[1024 * 8];
// while (zList.hasMoreElements()) {
// // 从ZipFile中得到一个ZipEntry
// ze = (ZipEntry) zList.nextElement();
// if (ze.isDirectory()) {
// continue;
// }
// // 以ZipEntry为参数得到一个InputStream,并写到OutputStream中
// OutputStream os = new BufferedOutputStream(new
// FileOutputStream(getRealFileName(outFileName, ze.getName())));
// InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
// int readLen = 0;
// while ((readLen = is.read(buf, 0, 1024 * 8)) != -1) {
// os.write(ciphers.doFinal(buf), 0, readLen);
// }
// is.close();
// os.close();
// // //Log.i("ZipManager", "[releaseZipToFile]"+"Extracted: " +
// // ze.getName());
// }
// zfile.close();
// }

/**
* 取得指定目录下的所有文件列表,包括子目录.
*
* @param baseDir
* File 指定的目录
* @return 包含java.io.File的List
*/
public static List<File> getSubFiles(File baseDir) {
List<File> ret = new ArrayList<File>();
// File base=new File(baseDir);
File[] tmp = baseDir.listFiles();
for (int i = 0; i < tmp.length; i++) {
if (tmp[i].isFile()) {
ret.add(tmp[i]);
}
if (tmp[i].isDirectory()) {
ret.addAll(getSubFiles(tmp[i]));
}
}
return ret;
}

/**
* 给定根目录,返回一个相对路径所对应的实际文件名.
*
* @param baseDir
* 指定根目录
* @param absFileName
* 相对路径名,来自于ZipEntry中的name
* @return java.io.File 实际的文件
* @throws IOException
*/
private static File getRealFileName(String baseDir, String absFileName) throws IOException {
String[] dirs = absFileName.split("/");
// System.out.println(dirs.length);
File ret = new File(baseDir);
// System.out.println(ret);
if (dirs.length > 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);
}
}
if (!ret.exists()) {
ret.mkdirs();
}
String parentPath = ret.getAbsolutePath();
ret = new File(ret, new String(dirs[dirs.length - 1].getBytes()));
if (!ret.exists()) {
try {
ret.createNewFile();
} catch (Exception e) {
String fileName = new String(dirs[dirs.length - 1].getBytes());
int idx = fileName.lastIndexOf(".");
String ext = "";
if (idx >= 0) {
ext = fileName.substring(idx);
}
ret = new File(parentPath, "" + System.currentTimeMillis() + ext);
ret.createNewFile();
}
}
return ret;
}

/**
* 给定根目录,返回另一个文件名的相对路径,用于zip文件中的路径.
*
* @param baseDir
* java.lang.String 根目录
* @param realFileName
* java.io.File 实际的文件名
* @return 相对文件名
*/
public static String getAbsFileName(String baseDir, File realFileName) {
File real = realFileName;
File base = new File(baseDir);
String ret = real.getName();
while (true) {
real = real.getParentFile();
if (real == null)
break;
if (real.equals(base))
break;
else {
ret = real.getName() + "/" + ret;
}
}
return ret;
}

@SuppressWarnings("unchecked")
public void testReadZip(String zipPath, String outPath) throws Exception {
ZipFile zfile = new ZipFile(zipPath);
System.out.println(zfile.getName());
Enumeration zList = zfile.entries();
ZipEntry ze = null;
byte[] buf = new byte[1024];
while (zList.hasMoreElements()) {
// 从ZipFile中得到一个ZipEntry
ze = (ZipEntry) zList.nextElement();
if (ze.isDirectory()) {
continue;
}
// 以ZipEntry为参数得到一个InputStream,并写到OutputStream中
OutputStream os = new BufferedOutputStream(new FileOutputStream(getRealFileName(outPath, 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();
//Log.i("ZipManager", "[testReadZip]" + "Extracted: " + ze.getName());
}
zfile.close();
}

public static byte[] convertStringtoGzip(List<String> contents) {
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
GZIPOutputStream gop = null;
try {
gop = new GZIPOutputStream(arrayOutputStream);
for (String content : contents) {
byte[] contentByte = content.getBytes();
// //Log.i("SPACE", content);
gop.write(contentByte, 0, contentByte.length);
}
gop.finish();
} catch (Exception e) {
return null;
} finally {
try {
gop.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return arrayOutputStream.toByteArray();
}

@SuppressWarnings("static-access")
public static void main(String args[]) {
// ZipManager manager = new ZipManager();
// try {
// //manager.unZip("c:\\testNpk.npk", "c:\\test");
// } catch (Exception e) {
// }
// System.out.println("over");
}

}

猜你喜欢

转载自gybin.iteye.com/blog/1824955