利用java解压,并重命名

2023-03-14,,

由于工作需要,写了一个小工具,利用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解压,并重命名.doc》

下载本文的Word格式文档,以方便收藏与打印。