利用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 ...
随机推荐
- python跨平台注释
使python程序运行在window以外的平台上 !# user/bin/python
- Myeclipse加载php插件
下载PHPEclipse-1.2.3.200910091456PRD-bin.zip 解压缩后.发现内容包含:两个目录features和plugins,一个xml文件site.xml 全部扔进myec ...
- wpf 寻找TreeView的子元素,并对其进行操作
//itemsControl 开始为指定的TreeView控件 item为TreeView子元素 private void PareItems(ItemsControl itemsControl, ...
- log4j2.xml日志文件设置文件路径
笔者最近的项目里使用了spring,spring通过web.xml配置监听器,在web启动时web.root系统变量,以供其他变量使用,例如 在属性文件里使用${web.root}以取得完整路径,项目 ...
- 十五、Collections.sort(<T>, new Comparator<T>() {})针对字符串排序
1.排序对象全是字母组成,可以根据ASCII编码表排序 package com.abcd; public class Person{ private String name; private int ...
- dskinlite(uieasy mfc界面库)使用记录4:绘制动态元素(listbox)
效果图: XML代码: 299行的headerctrl只针对listview有效,这里是listbox,忽略 wirelessName,wirelessStatus,wirelessSignal会通过 ...
- ASP.NET Core Web API 如何 数据分页 以及遇到'OFFSET' 附近有语法错误
最近领导叫我做的一个B/S端的小项目,突发奇想想用到core web api 今天写数据分页的时候,就想着 用linq分页查询吧,直接上代码 _context.Skip(Size * (PageNum ...
- new delate he typedef的含义
new: new 类型[初值] 如: new int ; //开辟一个存放整数的存储空间,返回一个指向该存储空间的 ...
- shapefile添加字段 设置文件名为字段内容
转眼间,这一年又结束了,再记录一点知识吧 同事说他有好多shapefile,想给每个shapefile添加一字段,并设置该字段的内容为shapefile文件名,想着用arcpy实现,于是有了下面的代码 ...
- SpringBoot图片上传
毕设终于写到头像上传了,本来想用Vue写来着,但是一直不顺利,还是对Vue用的不太熟.所以就用jquery写了. 首先添加以下标签 <img id="avatarPreview&quo ...