解压和压缩文件

1.解压文件

1.1解压zip文件,用到的是apache.tools.zip下的包

代码如下:

/**

* @param sourceFileName
*            要解压缩的zip文件
* @param desDir
*            解压缩到的目录
* @throws IOException
*/
public static String unZip(String sourceFileName, String desDir)
throws IOException {
// 创建压缩文件对象
ZipFile zf = new ZipFile(new File(sourceFileName));
// 获取压缩文件中的文件枚举
Enumeration<ZipEntry> en = zf.getEntries();
int length = 0;
byte[] b = new byte[1024];
// 提取压缩文件夹中的所有压缩实例对象
while (en.hasMoreElements()) {
ZipEntry ze = en.nextElement();
// 创建解压缩后的文件实例对象
File f = new File(desDir + File.separator + ze.getName());
// 如果当前压缩文件中的实例对象是文件夹,就在解压缩后的文件夹中创建该文件
if (ze.isDirectory()) {
f.mkdirs();
} else {
// 如果当前解压缩文件的父级文件没有创建的话,则创建父级文件夹
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
// 将当前文件的内容写入解压后的文件夹中
// f = new File(desDir + File.separator + DateUtil.nowDate().getTime() + ze.getName());
String newName = ze.getName().substring(0, ze.getName().lastIndexOf("."));
newName = new
Name + DateUtil.nowDate().getTime();
newName = newName + ze.getName().substring(ze.getName().lastIndexOf("."));
f = new File(desDir + File.separator + newName);
OutputStream outputStream = new FileOutputStream(f);
InputStream inputStream = zf.getInputStream(ze);
while ((length = inputStream.read(b)) > 0) {
outputStream.write(b, 0, length);
}


inputStream.close();
outputStream.close();
}
}
zf.close();
new File(sourceFileName).delete();
System.out.println("******************解压完毕********************");
return desDir;
}

1.2解压rar文件

代码如下:

/**
* 解压rar格式压缩包。
* 对应的是java-unrar-0.3.jar,但是java-unrar-0.3.jar又会用到commons-logging-1.1.1.jar
*/
public static String unrar(String sourceRar, String destDir)
throws Exception {
Archive a = null;
FileOutputStream fos = null;
a = new Archive(new File(sourceRar));
FileHeader fh = a.nextFileHeader();
while (fh != null) {
if (!fh.isDirectory()) {
// 1 根据不同的操作系统拿到相应的 destDirName 和 destFileName
// String compressFileName = fh.getFileNameString().trim();
String compressFileName = fh.getFileNameW().trim();
if ("".equals(compressFileName)) {
compressFileName = fh.getFileNameString().trim();
}
String destFileName = "";
String destDirName = "";
String newName = "";
// 非windows系统
if (File.separator.equals("/")) {
destFileName = destDir + File.separator
+ compressFileName.replaceAll("\\\\", "/");
//防止上传到ftp时重名,导致文件被覆盖
newName = destFileName.substring(0, destFileName.lastIndexOf(".")) + DateUtil.nowDate().getTime();
newName = newName + destFileName.substring(destFileName.lastIndexOf("."));
destDirName = newName.substring(0,
destFileName.lastIndexOf("/"));
// windows系统
} else {
destFileName = destDir + File.separator
+ compressFileName.replaceAll("/", "\\\\");
//防止上传到ftp时重名,导致文件被覆盖
newName = destFileName.substring(0, destFileName.lastIndexOf(".")) + DateUtil.nowDate().getTime();
newName = newName + destFileName.substring(destFileName.lastIndexOf("."));
destDirName = newName.substring(0,
destFileName.lastIndexOf("\\"));
}
// 2创建文件夹
File dir = new File(destDirName);
if (!dir.exists() || !dir.isDirectory()) {
dir.mkdirs();
}
// 3解压缩文件
fos = new FileOutputStream(new File(newName));
a.extractFile(fh, fos);
fos.close();
fos = null;
}
fh = a.nextFileHeader();
}
a.close();
// a = null;
new File(sourceRar).delete();
return destDir;
}

2.生成zip文件

/**
* 创建临时文件夹,并生成zip
* @throws Exception 
*/
@Override
public String createAndZip(String[] recordIdArr) throws Exception {
String path = FileUtil.PATH + "RSRC";
File file = new File(path);
if(!file.exists()){
file.mkdir();
}
for(String recordId : recordIdArr){
file = new File(path + File.separator + recordId);
if(!file.exists()){
file.mkdir();
}
// for(Object recordType : RecordType.values()){
// file = new File(path + File.separator + recordId + File.separator + recordType.toString());
// if(!file.exists()){
// file.mkdir();
// }
// }
//查询档案类型,并创建对应的多级文件目录
List<TreeInfo> treeList = treeService.searchAll(); 
TreeInfo treeUtils = TreeInfo.buildTree(treeList);
List<TreeInfo> trees = treeUtils.getChildren();
for(TreeInfo tree : trees){
String filePath = path + File.separator + recordId;
createDir(tree, filePath);
}
}
// FileUtil.zip(path, path+".zip");
File[] files = new File(path).listFiles();
List<File> filesList = new ArrayList<File>();
for(File f : files){
filesList.add(f);
}
FileUtil.toZip(filesList, new File(path + ".zip"), "", 9);
return path + ".zip";
}


public static void toZip(List<File> files,File zipFile,String path,int level)throws Exception{
File zipParnt = zipFile.getParentFile();
if(!zipParnt.exists()){
zipParnt.mkdirs();
}
if(path == null){
path = "";
}else if(path.length() > 0 && !path.endsWith(File.separator)){
path += File.separator;
}
//ZIP输出流
FileOutputStream fos = null;
ZipOutputStream zos = null;
try{
//创建ZIP输出流
fos = new FileOutputStream(zipFile);
//解决中文的关键所在
zos = new ZipOutputStream(fos);
//设置压缩级别
zos.setLevel(level < 0 ? 0 : (level > 9 ? 9 : level));
//开始压缩文件列表
Set<String> entryNames = new HashSet<String>();
int num = 1;
for(File f : files){
if(f.exists()){
//以文件名为entry名,如重复则前面加数字
String entryName = f.getName();
while(entryNames.contains(entryName)){
entryName = ("("+num+++")") + f.getName();
}
writeEntry(zos,f,path,entryName);
entryNames.add(entryName);
}
}
}finally{
//关闭ZIP输出流
try {
zos.close();
} catch (Exception e) {}
try {
fos.close();
} catch (Exception e) {}
}
}


private static void writeEntry(ZipOutputStream zos,File f,String path,String entryName)throws Exception{
//如果是目录
if(f.isDirectory()){
File[] list = f.listFiles();
//如果为空目录,也加入压缩文件
if(list.length == 0){
zos.putNextEntry(new ZipEntry(path + entryName + File.separator));
}else{
path = path + f.getName() + File.separator;
for(File fl : list){
writeEntry(zos, fl,path,fl.getName());
}
}
return;
}
//文件输入流
FileInputStream fis = null;
BufferedInputStream bis = null;
try{
//创建文件输入流
fis = new FileInputStream(f);
bis = new BufferedInputStream(fis);
//根据当前待压缩文件添加压缩条目
zos.putNextEntry(new ZipEntry(path + entryName));
//写入条目内容
byte[] buf = new byte[1024];
int len;
while((len = bis.read(buf)) != -1){
zos.write(buf,0,len);
}
}finally{
//关闭文件输入流
try {
bis.close();
} catch (Exception e) {}
try {
fis.close();
} catch (Exception e) {}
}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值