Java文件压缩与解压缩(二)(四)

2014-11-24 10:55:43 · 作者: · 浏览: 2
);
}
}
}
}
/**
* @param dirPath 将被压缩文件所在目录
* @param willZipFile 将被压缩的文件
* @return
*/
//生成的是每个文件的完整路径(从最外层文件夹至文件本身)
//这样生成的zipEntry就记录了原来的目录层次.解压后才保持原样
public String getEntryName(String dirPath, File willZipFile) {
if (!dirPath.endsWith(File.separator)) {
dirPath += File.separator;
}
String willZipFilePath=willZipFile.getAbsolutePath();
if (willZipFile.isDirectory()) {
willZipFilePath+="/";
}
int index=willZipFilePath.indexOf(dirPath);
System.out.println("xx返回的 entryName="+ willZipFilePath.substring(index+dirPath.length()));
return willZipFilePath.substring(index+dirPath.length());
}
/**
* @param zipedFileName 待解压zip文件
* @param unzipDirPath 文件解压后的最外层文件名
* @throws IOException
*/
public void unZipFile(String zipedFileName,String unzipDirPath) throws Exception{
if (!unzipDirPath.endsWith(File.separator)) {
unzipDirPath+=File.separator;
}
try {
ZipFile zipedFile=new ZipFile(zipedFileName);
ZipEntry zipEntry=null;
String entryName=null;
String unzipedFileName=null;
Enumeration entrys=zipedFile.entries();
byte [] buffer=new byte[1024*8];
int len=0;
while (entrys.hasMoreElements()) {
zipEntry=(ZipEntry) entrys.nextElement();
entryName=zipEntry.getName();
unzipedFileName=unzipDirPath+entryName;
System.out.println("…………………以下为unZipFile()方法…………………………");
System.out.println("zipedFileName="+zipedFileName);
System.out.println("unzipDirPath="+unzipDirPath);
System.out.println("entryName="+entryName);
System.out.println("unzipedFileName="+unzipedFileName);
System.out.println("…………………以上为unZipFile()方法…………………………");
if (zipEntry.isDirectory()) {
//没有执行此代码
System.out.println("999999999999");
new File(unzipedFileName).mkdirs();
} else {
//总是执行该代码.因为压缩的时候是对每个文件进行压缩的.
new File(unzipedFileName).getParentFile().mkdirs();
}
FileOutputStream fos=null;
InputStream is=null;
File unzipedFile=new File(unzipedFileName);
if (unzipedFile.isDirectory()) {
File [] files=unzipedFile.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
fos=new FileOutputStream(file);
is=zipedFile.getInputStream(zipEntry);
while ((len=is.read(buffer))!=-1) {
fos.write(buffer, 0, len);
}
}
}else{
fos=new FileOutputStream(unzipedFile);
is=zipedFile.getInputStream(zipEntry);
while ((len=is.read(buffer))!=-1) {
fos.write(buffer, 0, len);
}
}
//这里需要修改
//fos.close();