Java文件压缩与解压缩(三)(五)
;
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();
//is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/////////////////////////////////////////////////////////////////////////////////////
/**
* 该方法将一个给定路径的文件压缩
* @param willZipPath 待压缩文件的路径
* @param zipedPath 该文件压缩后的路径
*/
public void zip2(String willZipPath,String zipedPath){
try {
File willZipFile=new File(willZipPath);
File zipedFile=new File(zipedPath);
ZipOutputStream zos=new ZipOutputStream(new FileOutputStream(zipedFile));
if (willZipFile.isFile()) {
fileToZip2(willZipPath, zos);
}
if (willZipFile.isDirectory()) {
dirToZip2(willZipPath,willZipFile, zos);
}
//方法调用完成后关闭流
zos.close();
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* @param willZipFilePath 待压缩文件的路径
* @param zos 压缩文件输出流
* 1 关于以下两句代码
* ZipEntry entry = new ZipEntry();
* zos.putNextEntry(entry);
* 把生成的ZipEntry对象加入到压缩文件中
* 之后往压缩文件中写入的内容均放在该ZipEntry对象中
*
* 2 fis.close()但是不能在此处zos.close()
* 因为该zos是上一方法传递过来的.可能在压缩目录的时候会
* 再次使用到该zos流.若此时关闭,则导致目录中的一个文件
* 被压缩
*/
public void fileToZip2(String willZipFilePath,ZipOutputStream zos){
try {
File willZipFile=new File(willZipFilePath);
ZipEntry entry = new ZipEntry(getEntryName2(willZipFilePath, willZipFile));
zos.putNextEntry(entry);
FileInputStream fis = new FileInputStream(willZipFilePath);
int len = 0;
while ((len = fis.read()) != -1){
zos.write(len);
}
fis.close();
//zos.closeEntry();
//流关闭错误!
//zos.close();
} catch (Exception e) {
}
}
/**
* @param willZipDirctoryPath 原目录所在路径
* @param willZipedDirectory 原目录
* @param zos 压缩流
*/
public void dirToZip2(String willZipDirctoryPath,File willZipedDirectory, ZipOutputStream zos) {
if (willZipedDirectory.isDirectory()) {
File[] files = willZipedDirectory.listFiles();
//处理空文件夹的情况
if (files.length==0) {
ZipEntry zipEntry=new ZipEntry
(getEntryName2(willZipDirctoryPath, willZipedDirectory)+"/");
try {
zos.putNextEntry(zipEntry);
//zos.flush();
//zos.closeEntry();
} catch (Exception e) {
e.printStackTrace();
}
return;
}
for (int i = 0; i < files.length; i++) {
File file = fi