利用java解压,并重命名


由于工作需要,写了一个小工具,利用java来解压文件然后对文件进行重命名

主要针对三种格式,分别是zip,rar,7z,经过我的多次实践我发现网上的类库并不能解压最新的压缩格式

对于zip格式:

maven依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.9</version>
</dependency>

代码如下:

 1  private static Boolean unzip(String fileName, String unZipPath, String rename) throws Exception {
 2         boolean flag = false;
 3         File zipFile = new File(fileName);
 4 
 5         ZipFile zip = null;
 6         try {
 7             //指定编码,否则压缩包里面不能有中文目录
 8             zip = new ZipFile(zipFile, Charset.forName("GBK"));
 9 
10             for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
11                 ZipEntry entry = null;
12                 try {
13                     entry = (ZipEntry) entries.nextElement();
14                 } catch (Exception e) {
15                     return flag;
16                 }
17 
18                 String zipEntryName = entry.getName();
19                 InputStream in = zip.getInputStream(entry);
20                 String[] split = rename.split("\n");
21                 for (int i = 0; i < split.length; i++) {
22                     zipEntryName = zipEntryName.replace(split[i], " ");//这里可以替换原来的名字
23                 }
24                 String outPath = (unZipPath + zipEntryName).replace("/", File.separator); //解压重命名
25 
26                 //判断路径是否存在,不存在则创建文件路径
27                 File outfilePath = new File(outPath.substring(0, outPath.lastIndexOf(File.separator)));
28                 if (!outfilePath.exists()) {
29                     outfilePath.mkdirs();
30                 }
31                 //判断文件全路径是否为文件夹
32                 if (new File(outPath).isDirectory()) {
33                     continue;
34                 }
35                 //保存文件路径信息
36                 //urlList.add(outPath);
37 
38                 OutputStream out = new FileOutputStream(outPath);
39                 byte[] buf1 = new byte[2048];
40                 int len;
41                 while ((len = in.read(buf1)) > 0) {
42                     out.write(buf1, 0, len);
43                 }
44                 in.close();
45                 out.close();
46             }
47             flag = true;
48             //必须关闭,否则无法删除该zip文件
49             zip.close();
50         } catch (IOException e) {
51             flag = false;
52         }
53 
54 
55         return flag;
56 
57     }

对于zip的文件大部分可以解压但是我发现有些的中文编码得是UTF-8才能解压,因此设置成GBK 不是绝对的

7z格式的就和网上大部分的代码类似

maven依赖同上的

 1 public static Boolean apache7ZDecomp(String orgPath, String tarpath, String rename) {
 2         boolean flag = false;
 3         try {
 4             SevenZFile sevenZFile = new SevenZFile(new File(orgPath));
 5             SevenZArchiveEntry entry = sevenZFile.getNextEntry();
 6             while (entry != null) {
 7 
 8                 // System.out.println(entry.getName());
 9                 if (entry.isDirectory()) {
10 
11                     new File(tarpath + entry.getName()).mkdirs();
12                     entry = sevenZFile.getNextEntry();
13                     continue;
14                 }
15                 String entryName = entry.getName();
16                 String[] split = rename.split("\n");
17                 for (int i = 0; i < split.length; i++) {
18                     entryName = entryName.replace(split[i], "");//这里是对原来的名字进行替换,也可以写你想要换的名字
19                 }
20                 String tarpathFileName = (tarpath + entryName).replace("/", File.separator);
21                 File fileDir = new File(tarpath);
22                 if (!fileDir.exists()) {
23                     fileDir.mkdirs();
24                 }
25                 FileOutputStream out = new FileOutputStream(tarpathFileName);
26                 byte[] content = new byte[(int) entry.getSize()];
27                 sevenZFile.read(content, 0, content.length);
28                 out.write(content);
29                 out.close();
30                 entry = sevenZFile.getNextEntry();
31                 flag = true;
32             }
33             sevenZFile.close();
34         } catch (FileNotFoundException e) {
35             return flag;
36         } catch (IOException e) {
37             return flag;
38         }
39         return flag;
40     }

还有一种是用这个类库:                                                                                    

<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) {
 2 
 3         final File file = new File(targetFilePath);  4         if (!file.exists()) {  5  file.mkdirs();  6  }  7         RandomAccessFile randomAccessFile = null;  8         IInArchive inArchive = null;  9 
10         try { 11             randomAccessFile = new RandomAccessFile(filepath, "r"); 12             inArchive = SevenZip.openInArchive(null, 13                     new RandomAccessFileInStream(randomAccessFile)); 14 
15             ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface(); 16 
17             for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) { 18                 final int[] hash = new int[]{0}; 19                 if (!item.isFolder()) { 20  ExtractOperationResult result; 21 
22                     final long[] sizeArray = new long[1]; 23                     result = item.extractSlow(new ISequentialOutStream() { 24                         public int write(byte[] data) throws SevenZipException { 25 
26                             FileOutputStream fos = null; 27                             try { 28                                 String fileName = item.getPath(); 29                                 String[] split = rename.split("\r\n"); 30                                 for (int i = 0; i < split.length; i++) { 31                                     fileName = fileName.replace(split[i], ""); 32  } 33 
34                                 File tarFile = new File(file + File.separator + fileName); 35 
36                                 if (!tarFile.getParentFile().exists()) { 37  tarFile.getParentFile().mkdirs(); 38  } 39  tarFile.createNewFile(); 40                                 fos = new FileOutputStream(tarFile.getAbsolutePath()); 41  fos.write(data); 42  fos.close(); 43 
44                             } catch (FileNotFoundException e) { 45 
46                             } catch (IOException e) { 47 
48  } 49 
50                             hash[0] ^= Arrays.hashCode(data); 51                             sizeArray[0] += data.length; 52                             return data.length; 53  } 54  }); 55                     if (result == ExtractOperationResult.OK) { 56                         // System.out.println(String.format("%9X | %10s | %s", //
57                         // hash[0], sizeArray[0], item.getPath()));
58                     } else { 59                         // System.err.println("Error extracting item: " + result);
60  } 61  } 62  } 63         } catch (Exception e) { 64  e.printStackTrace(); 65             System.exit(1); 66         } finally { 67             if (inArchive != null) { 68                 try { 69  inArchive.close(); 70                 } catch (SevenZipException e) { 71  e.printStackTrace(); 72  } 73  } 74             if (randomAccessFile != null) { 75                 try { 76  randomAccessFile.close(); 77                 } catch (IOException e) { 78  e.printStackTrace(); 79  } 80  } 81  } 82     }
  
  <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最简单直接,然后压缩的话基本上大部分都可以压缩,就不写上压缩的代码了

    


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM