java压缩解压代码 java实现解压缩( 二 )


{
throw new ParameterException(ICommonResultCode.INVALID_PARAMETER, "zipPath must not be the child directory of srcPath.");
}
//判断压缩文件保存的路径是否存在,如果不存在,则创建目录
File zipDir = new File(zipPath);
if (!zipDir.exists() || !zipDir.isDirectory())
{
zipDir.mkdirs();
}
//创建压缩文件保存的文件对象
String zipFilePath = zipPath + File.separator + zipFileName;
File zipFile = new File(zipFilePath);
if (zipFile.exists())
{
//检测文件是否允许删除,如果不允许删除,将会抛出SecurityException
SecurityManager securityManager = new SecurityManager();
securityManager.checkDelete(zipFilePath);
//删除已存在的目标文件
zipFile.delete();
}
cos = new CheckedOutputStream(new FileOutputStream(zipFile), new CRC32());
zos = new ZipOutputStream(cos);
//如果只是压缩一个文件,则需要截取该文件的父目录
String srcRootDir = srcPath;
if (srcFile.isFile())
{
int index = srcPath.lastIndexOf(File.separator);
if (index != -1)
{
srcRootDir = srcPath.substring(0, index);
}
}
//调用递归压缩方法进行目录或文件压缩
zip(srcRootDir, srcFile, zos);
zos.flush();
}
catch (Exception e)
{
throw e;
}
finally
{
try
{
if (zos != null)
{
zos.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
/**
* 解压缩zip包
* @param zipFilePath zip文件的全路径
* @param unzipFilePath 解压后的文件保存的路径
* @param includeZipFileName 解压后的文件保存的路径是否包含压缩文件的文件名 。true-包含;false-不包含
*/
@SuppressWarnings("unchecked")
public static void unzip(String zipFilePath, String unzipFilePath, boolean includeZipFileName) throws Exception
{
if (StringUtils.isEmpty(zipFilePath) || StringUtils.isEmpty(unzipFilePath))
{
throw new ParameterException(ICommonResultCode.PARAMETER_IS_NULL);
}
File zipFile = new File(zipFilePath);
//如果解压后的文件保存路径包含压缩文件的文件名,则追加该文件名到解压路径
if (includeZipFileName)
{
String fileName = zipFile.getName();
if (StringUtils.isNotEmpty(fileName))
{
fileName = fileName.substring(0, fileName.lastIndexOf("."));
}
unzipFilePath = unzipFilePath + File.separator + fileName;
}
//创建解压缩文件保存的路径
File unzipFileDir = new File(unzipFilePath);
if (!unzipFileDir.exists() || !unzipFileDir.isDirectory())
{
unzipFileDir.mkdirs();
}
//开始解压
ZipEntry entry = null;
String entryFilePath = null, entryDirPath = null;
File entryFile = null, entryDir = null;
int index = 0, count = 0, bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
ZipFile zip = new ZipFile(zipFile);
EnumerationZipEntry entries = (EnumerationZipEntry)zip.entries();
//循环对压缩包里的每一个文件进行解压
while(entries.hasMoreElements())
{
entry = entries.nextElement();
//构建压缩包中一个文件解压后保存的文件全路径
entryFilePath = unzipFilePath + File.separator + entry.getName();
//构建解压后保存的文件夹路径
index = entryFilePath.lastIndexOf(File.separator);
if (index != -1)
{
entryDirPath = entryFilePath.substring(0, index);
}
【java压缩解压代码 java实现解压缩】else
{
entryDirPath = "";
}
entryDir = new File(entryDirPath);

推荐阅读