Java文件压缩与解压缩(二)(二)
fileToZip(willZipDirPath, willZipFile, zos);
System.out.println("…………………最外层压缩文件结束………………………");
}
if (willZipFile.isDirectory()) {
System.out.println("…………………最外层开始压缩目录………………………");
dirToZip(willZipDirPath, willZipFile, zos);
System.out.println("…………………最外层压缩目录结束………………………");
}
// 关闭流!!!
zos.close();
System.out.println("…………………以上为zip()方法…………………………");
}
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* @param dirPath 被压缩文件所在目录
* @param willZipFile 被压缩文件的名称
* @param zos 输出流
*/
public void fileToZip(String dirPath, File willZipFile,ZipOutputStream zos){
FileInputStream fis=null;
ZipEntry zipEntry=null;
byte [] buffer=new byte[1024*8];
int len=0;
if (willZipFile.isFile()) {
try {
fis=new FileInputStream(willZipFile);
zipEntry=new ZipEntry(getEntryName(dirPath, willZipFile));
zos.putNextEntry(zipEntry);
System.out.println("…………………以下为fileToZip()方法…………………………");
System.out.println("zipEntry.getName="+zipEntry.getName());
System.out.println("zipEntry.isDirectory="+zipEntry.isDirectory());
System.out.println("zipEntry.getSize="+zipEntry.getSize());
System.out.println("zipEntry.getTime="+zipEntry.getTime());
System.out.println("zipEntry.getComment="+zipEntry.getComment());
System.out.println("…………………以上为fileToZip()方法…………………………");
while((len=fis.read(buffer))!=-1){
zos.write(buffer, 0, len);
}
zos.closeEntry();
fis.close();
} catch (Exception e) {
}
}
}
/**
* @param dirPath 被压缩目录所在的上级目录
* @param willZipDir 被压缩目录
* @param zos 输出流
*/
public void dirToZip(String dirPath, File willZipDir, ZipOutputStream zos) {
if (willZipDir.isDirectory()) {
File[] files = willZipDir.listFiles();
//处理-->该文件夹下无文件
if (files.length==0) {
ZipEntry zipEntry=new ZipEntry(getEntryName(dirPath, willZipDir));
System.out.println("xxxxxxxxxxxxxxxx "+zipEntry.getName());
try {
zos.putNextEntry(zipEntry);
//zos.closeEntry();
} catch (Exception e) {
e.printStackTrace();
}
return;
}
//处理-->该文件夹下的所有文件
for (int i = 0; i < files.length; i++) {
File file = files[i];
//若是文件,递归调用fileToZip()
if (file.isFile()) {
System.out.println("xxxxxxxxxx内层开始fileToZip()方法xxxxxxxxxx");
fileToZip(dirPath, file, zos);
System.out.println("xxxxxxxxxx内层fileToZip()方法结束xxxxxxxxxx");
}
//若是文件,递归调用dirToZip()
if (file.isDirectory()) {
System.out.println("xxxxxxxxxx内层开始dirToZip()方法xxxxxxxxxx");
dirToZip(dirPath, file, zos);
System.out.println("xxxxxxxxxx内层dirToZip()方法结束xxxxxxxxxx"