利用java解压,并重命名
由于工作需要,写了一个小工具,利用java来解压文件然后对文件进行重命名
主要针对三种格式,分别是zip,rar,7z,经过我的多次实践我发现网上的类库并不能解压最新的压缩格式
对于zip格式:
maven依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.9</version>
</dependency>
代码如下:
private static Boolean unzip(String fileName, String unZipPath, String rename) throws Exception {
boolean flag = false;
File zipFile = new File(fileName);
ZipFile zip = null;
try {
//指定编码,否则压缩包里面不能有中文目录
zip = new ZipFile(zipFile, Charset.forName("GBK"));
for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = null;
try {
entry = (ZipEntry) entries.nextElement();
} catch (Exception e) {
return flag;
}
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String[] split = rename.split("\n");
for (int i = 0; i < split.length; i++) {
zipEntryName = zipEntryName.replace(split[i], " ");//这里可以替换原来的名字
}
String outPath = (unZipPath + zipEntryName).replace("/", File.separator); //解压重命名
//判断路径是否存在,不存在则创建文件路径
File outfilePath = new File(outPath.substring(0, outPath.lastIndexOf(File.separator)));
if (!outfilePath.exists()) {
outfilePath.mkdirs();
}
//判断文件全路径是否为文件夹
if (new File(outPath).isDirectory()) {
continue;
}
//保存文件路径信息
//urlList.add(outPath);
OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[2048];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
in.close();
out.close();
}
flag = true;
//必须关闭,否则无法删除该zip文件
zip.close();
} catch (IOException e) {
flag = false;
}
return flag;
}
对于zip的文件大部分可以解压但是我发现有些的中文编码得是UTF-8才能解压,因此设置成GBK 不是绝对的
7z格式的就和网上大部分的代码类似
maven依赖同上的
public static Boolean apache7ZDecomp(String orgPath, String tarpath, String rename) {
boolean flag = false;
try {
SevenZFile sevenZFile = new SevenZFile(new File(orgPath));
SevenZArchiveEntry entry = sevenZFile.getNextEntry();
while (entry != null) {
// System.out.println(entry.getName());
if (entry.isDirectory()) {
new File(tarpath + entry.getName()).mkdirs();
entry = sevenZFile.getNextEntry();
continue;
}
String entryName = entry.getName();
String[] split = rename.split("\n");
for (int i = 0; i < split.length; i++) {
entryName = entryName.replace(split[i], "");//这里是对原来的名字进行替换,也可以写你想要换的名字
}
String tarpathFileName = (tarpath + entryName).replace("/", File.separator);
File fileDir = new File(tarpath);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
FileOutputStream out = new FileOutputStream(tarpathFileName);
byte[] content = new byte[(int) entry.getSize()];
sevenZFile.read(content, 0, content.length);
out.write(content);
out.close();
entry = sevenZFile.getNextEntry();
flag = true;
}
sevenZFile.close();
} catch (FileNotFoundException e) {
return flag;
} catch (IOException e) {
return flag;
}
return flag;
}
还有一种是用这个类库:
<dependency>
<groupId>net.sf.sevenzipjbinding</groupId>
<artifactId>sevenzipjbinding</artifactId>
<version>9.20-2.00beta</version>
</dependency> <dependency>
<groupId>net.sf.sevenzipjbinding</groupId>
<artifactId>sevenzipjbinding-all-platforms</artifactId>
<version>9.20-2.00beta</version>
</dependency> 1 public static void un7ZipFile(String filepath, String targetFilePath, String rename) {
final File file = new File(targetFilePath);
if (!file.exists()) {
file.mkdirs();
}
RandomAccessFile randomAccessFile = null;
IInArchive inArchive = null; try {
randomAccessFile = new RandomAccessFile(filepath, "r");
inArchive = SevenZip.openInArchive(null,
new RandomAccessFileInStream(randomAccessFile)); ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface(); for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[]{0};
if (!item.isFolder()) {
ExtractOperationResult result; final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException { FileOutputStream fos = null;
try {
String fileName = item.getPath();
String[] split = rename.split("\r\n");
for (int i = 0; i < split.length; i++) {
fileName = fileName.replace(split[i], "");
} File tarFile = new File(file + File.separator + fileName); if (!tarFile.getParentFile().exists()) {
tarFile.getParentFile().mkdirs();
}
tarFile.createNewFile();
fos = new FileOutputStream(tarFile.getAbsolutePath());
fos.write(data);
fos.close(); } catch (FileNotFoundException e) { } catch (IOException e) { } hash[0] ^= Arrays.hashCode(data);
sizeArray[0] += data.length;
return data.length;
}
});
if (result == ExtractOperationResult.OK) {
// System.out.println(String.format("%9X | %10s | %s", //
// hash[0], sizeArray[0], item.getPath()));
} else {
// System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
e.printStackTrace();
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>3.0.0</version>
</dependency>
public static boolean unrar(String rarFileName, String outFilePath, String rename) throws Exception {
try {
Archive archive = new Archive(new File(rarFileName), new UnrarProcessMonitor(rarFileName));
if (archive == null) {
throw new FileNotFoundException(rarFileName + " NOT FOUND!");
}
if (archive.isEncrypted()) {
throw new Exception(rarFileName + " IS ENCRYPTED!");
}
List<FileHeader> files = archive.getFileHeaders();
for (FileHeader fh : files) {
if (fh.isEncrypted()) {
throw new Exception(rarFileName + " IS ENCRYPTED!");
}
String fileName = fh.getFileNameW().isEmpty() ? fh.getFileNameString() : fh.getFileNameW();
String[] split = rename.split("\n");
for (int i = 0; i < split.length; i++) {
fileName = fileName.replace(split[i], ""); //解压重命名
}
if (fileName != null && fileName.trim().length() > 0) {
String saveFileName = outFilePath + File.separator + fileName;
File saveFile = new File(saveFileName);
File parent = saveFile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
if (!saveFile.exists()) {
saveFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(saveFile);
try {
archive.extractFile(fh, fos);
fos.flush();
fos.close();
} catch (RarException e) {
} finally {
}
}
}
return true;
} catch (Exception e) {
System.out.println("failed.");
return false;
}
}
//对解压rar文件进度的监控
public class UnrarProcessMonitor implements UnrarCallback {
private String fileName;
public UnrarProcessMonitor(String fileName) {
this.fileName = fileName;
}
/**
* 返回false的话,对于某些分包的rar是没办法解压正确的
* */
@Override
public boolean isNextVolumeReady(Volume volume) {
try {
fileName = ((FileVolume) volume).getFile().getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public void volumeProgressChanged(long l, long l1) {
//输出进度
System.out.println("Unrar "+fileName+" rate: "+(double)l/l1*100+"%");
}
}
最后就是如果三种方法都无法解压我们就应该调用cmd来用WinRar进行解压
public static boolean unfile(String zipFile,String outFilePath,int mode){
boolean flag=false;
try{
File file = new File(zipFile);
String fileName = file.getName();
if(mode == 1)
{
outFilePath += File.separator; //文件当前路径下
}else{
outFilePath += File.separator+fileName.substring(0,fileName.length()-4)+File.separator;
}
File tmpFileDir = new File(outFilePath);
tmpFileDir.mkdirs();
String unrarCmd = "C:\\Program Files\\WinRAR\\WinRar e ";
unrarCmd += zipFile + " " + outFilePath;
try {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(unrarCmd);
InputStream inputStream=p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
while (br.readLine()!=null){
}
p.waitFor();
br.close();
inputStream.close();
p.getErrorStream().close();
p.getOutputStream().close();
flag=true;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}catch(Exception e){
}
return flag;
}
以上就是解压的方法,总体坐下来感觉还是调用cmd最简单直接,然后压缩的话基本上大部分都可以压缩,就不写上压缩的代码了
利用java解压,并重命名的更多相关文章
- 关于Java解压文件的一些坑及经验分享(MALFORMED异常)
文章也已经同步到我的csdn博客: http://blog.csdn.net/u012881584/article/details/72615481 关于Java解压文件的一些坑及经验分享 就在本周, ...
- Java解压和压缩带密码的zip或rar文件(下载压缩文件中的选中文件、向压缩文件中新增、删除文件)
JAVA 实现在线浏览管理zip和rar的工具类 (有密码及无密码的)以及下载压缩文件中的选中文件(向压缩文件中新增.删除文件) 这是之前的版本 JAVA 解压压缩包中指定文件或实现压缩文件的预览及下 ...
- JAVA解压.Z及.ZIP文件
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-compress --> <dependency ...
- java利用zip解压slpk文件
public static void main(String[] args) { File file = new File("C:\\Users\\Administrator\\Deskto ...
- 【java】 java 解压tar.gz读取内容
package com.xwolf.stat.util; import com.alibaba.druid.util.StringUtils; import com.alibaba.fastjson. ...
- Java解压上传zip或rar文件,并解压遍历文件中的html的路径
1.本文只提供了一个功能的代码 public String addFreeMarker() throws Exception { HttpSession session = request.getSe ...
- java 解压 zip 包并删除
需求是这样的, 在服务器上有 运营上传的zip 包,内容是用户的照片,我需要做的是 获取这些照片上传,并保存到 数据库. 这里面的 上传照片,保存数据库都不难,主要问题是解压zip包,和删除zip ...
- Java 解压zip压缩包
因为最近项目需要批量上传文件,而这里的批量就是将文件压缩在了一个zip包里,然后读取文件进行解析文件里的内容. 因此需要先对上传的zip包进行解压.以下直接提供代码供参考: 1.第一个方法是用于解压z ...
- java解压多层目录中多个压缩文件和处理压缩文件中有内层目录的情况
代码: package com.xiaobai; import java.io.File; import java.io.FileOutputStream; import java.io.IOExce ...
随机推荐
- PHP 浮点型转整型的一个奇怪现象
起因 最近通过一个学长的题了解php弱类型的时候,发现了一个奇怪的现象. 正文 主要问题在这样一段代码: $c=(int)((0.1+$b)*10); 当$b=0.6,0.8以及其他值的时候都正常 将 ...
- 转:vue项目如何刷新当前页面
想必大家在刨坑vue的时候也遇到过下面情形:比如在删除或者增加一条记录的时候希望当前页面可以重新刷新或者如下面这种: 如果希望点击确定的时候,Dialog 对话框关闭的时候,当前http://loca ...
- 腾讯2019年暑期实习生招聘提前批在线笔试技术研究和数据分析方向t2(python)
小Q有一叠纸牌,一共有n张,从上往下依次编号为1~n.现在小Q要进行以下重复操作:把位于顶端的牌扔掉,把新的顶端的牌放到这叠牌的底部.小Q会一直操作到只剩下一张牌为止,小Q想知道每次扔掉的牌的编号.[ ...
- SCRUM管理之KPI与OKRs结合
以下内容是本人在担任ScrumMaster中的实际应用,供大家交流学习参考. 目录 1绩效考核原则 4 2绩效考核范围 4 3绩效计算 4 3.1KPI 4 3.1.1KPI指标评分表 4 3.1.2 ...
- python 下 判断操作系统
import platform OS = platform.system() # Windows, Linux, Darwin def get_sys(): if OS == 'Darwin': pr ...
- CentOS7 修改静态IP地址
Ip配置文件在/etc/sysconfig/network-scripts文件夹下,查找该文件的方法为: [root@localhost ~]# ll /etc/sysconfig/network-s ...
- 5个数组Array方法: indexOf、filter、forEach、map、reduce使用实例
ES5中,一共有9个Array方法 Array.prototype.indexOf Array.prototype.lastIndexOf Array.prototype.every Array.pr ...
- 微信小程序发送ajax
微信小程序通过 wx.request发送ajax请求 1. GET wx.request({ url: app.globalData.pubSiteUrl + 'user-information/ge ...
- Linux-01初级学习
刚刚接触 Linux学习中的一点笔记`02 ps:自己学习过程中的记录,略菜,给没学过的纯小白 配置网络 1.虚拟网卡 2.虚拟机服务 我的电脑-->管理-->服务 3.修改网络配置文件 ...
- 201771010134杨其菊《面向对象程序设计(java)》第十五周学习
第十五周学习总结 第一部分:理论知识 JAR文件: 应用程序首选项存储: Java Web Start JAR文件: 1.Java程序的打包:程序编译完成后,程序员将.class文件压缩打包为.jar ...