zip、rar格式文件解压缩处理

雨点打透心脏的1/2处 2023-06-23 13:11 91阅读 0赞

文章目录

  • zip、rar格式文件解压缩处理
    • 核心pom依赖引入
    • 核心工具类FileUtil.java
    • 统一接口
    • rar格式解压缩处理
    • zip格式解压缩处理

zip、rar格式文件解压缩处理

在相关业务场景中,批量文件处理,需要预先进行解压缩及拷贝处理

核心pom依赖引入

  1. <!-- 导入zip解压包 -->
  2. <dependency>
  3. <groupId>ant</groupId>
  4. <artifactId>ant</artifactId>
  5. <version>1.6.5</version>
  6. </dependency>
  7. <!-- 导入rar解压包 -->
  8. <dependency>
  9. <groupId>com.github.junrar</groupId>
  10. <artifactId>junrar</artifactId>
  11. <version>4.0.0</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>com.github.jnr</groupId>
  15. <artifactId>jnr-posix</artifactId>
  16. <version>3.0.50</version>
  17. </dependency>

核心工具类FileUtil.java

  1. public static boolean unPackagedFile(String filename,String dir){
  2. InfDecompress rarDecompress = null;
  3. if(filename.endsWith(".rar")){
  4. rarDecompress = new RarDecompress(); //需要用rar4格式的压缩包能被解析,高版本不行
  5. }else if(filename.endsWith(".zip")){
  6. rarDecompress = new ZipDecompress();
  7. }else{
  8. logger.error("不支持的解包扩展名格式");
  9. return false;
  10. }
  11. if(!rarDecompress.decompressFile(filename,dir)){
  12. logger.error(filename + "解压失败");
  13. return false;
  14. }
  15. return true;
  16. }
  17. public static int copyFilesOfDir(String srcDirPath, String desDirPath) {
  18. if (!srcDirPath.endsWith(File.separator)) {
  19. srcDirPath = srcDirPath + File.separator;
  20. }
  21. if (!desDirPath.endsWith(File.separator)) {
  22. desDirPath = desDirPath + File.separator;
  23. }
  24. File srcfile = new File(srcDirPath);
  25. if (srcfile.exists()) {
  26. String[] fileNames = srcfile.list();
  27. //及时是个空目录 也要创建一个空的目标目录
  28. if (fileNames != null) {
  29. if (!new File(desDirPath).exists()) {
  30. if (!new File(desDirPath).mkdirs()) {
  31. logger.error("{failed to mkdirs " + desDirPath + "}");
  32. return -1;
  33. }
  34. }
  35. }
  36. else {
  37. return -1;
  38. }
  39. for (String fileName : fileNames) {
  40. File fileToCopy = null;
  41. if (srcDirPath.endsWith(File.separator)) {
  42. fileToCopy = new File(srcDirPath + fileName);
  43. } else {
  44. fileToCopy = new File(srcDirPath + File.separator + fileName);
  45. }
  46. if (fileToCopy.isFile()) {
  47. //copy file
  48. FileInputStream inputStream = null;
  49. FileOutputStream outputStream = null;
  50. try {
  51. inputStream = new FileInputStream(fileToCopy);
  52. if (desDirPath.endsWith(File.separator)) {
  53. outputStream = new FileOutputStream(desDirPath + fileToCopy.getName());
  54. } else {
  55. outputStream = new FileOutputStream(desDirPath + File.separator + fileToCopy.getName());
  56. }
  57. byte[] buffer = new byte[10240];
  58. int len;
  59. while ((len = inputStream.read(buffer)) != -1) {
  60. outputStream.write(buffer, 0, len);
  61. }
  62. outputStream.flush();
  63. outputStream.close();
  64. inputStream.close();
  65. } catch (FileNotFoundException ex) {
  66. logger.error(ex.getMessage());
  67. return -1;
  68. } catch (IOException ex) {
  69. logger.error(ex.getMessage());
  70. return -1;
  71. } finally {
  72. }
  73. } else {
  74. continue;
  75. }
  76. }
  77. }
  78. return 0;
  79. }
  80. public static int copyFile(String srcFileNm,String DesFileNm)
  81. {
  82. InputStream input = null;
  83. OutputStream output = null;
  84. try{
  85. File inFile = new File(srcFileNm);
  86. File outFile = new File(DesFileNm);
  87. /*if(!outFile.exists())
  88. outFile.createNewFile();*/
  89. input = new FileInputStream(inFile);
  90. output = new FileOutputStream(outFile);
  91. byte[] buf = new byte[1024];
  92. int bytesRead;
  93. while ((bytesRead = input.read(buf)) > 0) {
  94. output.write(buf, 0, bytesRead);
  95. }
  96. }catch (Exception e){
  97. logger.error("copyFileToDstdir 文件拷贝失败,src:" + srcFileNm + " dst:" + DesFileNm + "errorMsg:" + e.getLocalizedMessage());
  98. return -1;
  99. }finally {
  100. try{
  101. if(input != null){
  102. input.close();
  103. }
  104. if(output != null){
  105. output.close();
  106. }
  107. }catch (IOException e){
  108. logger.error(e.getMessage());
  109. }
  110. }
  111. return 0;
  112. }
  113. public static int deleteDirRecursively(String absoluteDirPath)
  114. {
  115. File dir=new File(absoluteDirPath);
  116. if(!dir.isDirectory())
  117. {
  118. if(!dir.delete())
  119. {
  120. logger.error("delete file failed "+ dir.getAbsolutePath());
  121. return -1;
  122. }
  123. return 0;
  124. }
  125. else
  126. {
  127. String[] fileList=dir.list();
  128. for(String fileName:fileList)
  129. {
  130. String absolutePath=absoluteDirPath+File.separator+fileName;
  131. if(deleteDirRecursively(absolutePath)<0)
  132. {
  133. logger.error("delete file failed "+absolutePath);
  134. return -1;
  135. }
  136. }
  137. if(fileList.length==0)
  138. {
  139. if(!dir.delete())
  140. {
  141. logger.error(dir.getAbsolutePath()+" delele failed");
  142. return -1;
  143. }
  144. }
  145. }
  146. return 0;
  147. }
  148. /**
  149. * 从fileName全路径中,获取文件名称
  150. * @param fileName
  151. * @return
  152. */
  153. public static String getIndexOfFile(String fileName){
  154. if(fileName == null){
  155. return fileName;
  156. }
  157. if(fileName.lastIndexOf("\\") != -1){
  158. return fileName.substring(fileName.lastIndexOf("\\")+1);
  159. }
  160. if(fileName.lastIndexOf("/") != -1){
  161. return fileName.substring(fileName.lastIndexOf("/")+1);
  162. }
  163. return fileName;
  164. }

统一接口

  1. public interface InfDecompress {
  2. boolean decompressFile(String fn,String dest);
  3. }

rar格式解压缩处理

  1. import com.github.junrar.Archive;
  2. import com.github.junrar.rarfile.FileHeader;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import java.io.*;
  6. public class RarDecompress implements InfDecompress{
  7. private static Logger logger = LoggerFactory.getLogger(RarDecompress.class);
  8. @Override
  9. public boolean decompressFile(String fn,String dest) {
  10. Archive a = null;
  11. try {
  12. File inFile = new File(fn);
  13. a = new Archive(new FileInputStream(inFile));
  14. if(a!=null){
  15. FileHeader fh = a.nextFileHeader();
  16. while(fh != null){
  17. if(fh.isDirectory()){
  18. File fol = new File(dest + File.separator + fh.getFileNameString());
  19. fol.mkdirs();
  20. }else{
  21. String unpackFile = dest + File.separator + fh.getFileNameString().trim();
  22. File out = new File(unpackFile);
  23. if(!out.exists()){
  24. if (!out.getParentFile().exists()) {// 相对路径可能多级,可能需要创建父目录.
  25. out.getParentFile().mkdirs();
  26. }
  27. out.createNewFile();
  28. }
  29. FileOutputStream os = new FileOutputStream(out);
  30. a.extractFile(fh, os);
  31. os.close();
  32. if(unpackFile.endsWith(".rar") || unpackFile.endsWith(".zip")){ //子文件下还有被压缩的文件
  33. UnPackage.unPackagedFile(unpackFile,unpackFile.substring(0,unpackFile.lastIndexOf(File.separator)));
  34. }
  35. }
  36. fh = a.nextFileHeader();
  37. }
  38. }else {
  39. logger.error("Rar decompressFile异常");
  40. return false;
  41. }
  42. a.close();
  43. return true;
  44. }catch (Exception e){
  45. logger.error("解压" + fn + "文件失败" + e.getLocalizedMessage());
  46. }
  47. return false;
  48. }
  49. }

zip格式解压缩处理

  1. import org.apache.tools.zip.ZipEntry;
  2. import org.apache.tools.zip.ZipFile;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import java.io.File;
  6. import java.io.FileOutputStream;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. import java.util.Enumeration;
  10. public class ZipDecompress implements InfDecompress{
  11. private static Logger logger = LoggerFactory.getLogger(ZipDecompress.class);
  12. @Override
  13. public boolean decompressFile(String fn,String dest) {
  14. try {
  15. ZipFile zip = new ZipFile(fn,"gbk");
  16. for (Enumeration entries = zip.getEntries(); entries.hasMoreElements(); ) {
  17. ZipEntry entry = (ZipEntry) entries.nextElement();
  18. String zipEntryName = entry.getName();
  19. String unpackFile = dest + File.separator + zipEntryName.trim();
  20. InputStream in = zip.getInputStream(entry);
  21. OutputStream out = new FileOutputStream(dest + File.separator + zipEntryName);
  22. if (new File(zipEntryName).isDirectory()) {
  23. continue;
  24. }
  25. byte[] buf1 = new byte[1024];
  26. int len;
  27. while ((len = in.read(buf1)) > 0) {
  28. out.write(buf1, 0, len);
  29. }
  30. in.close();
  31. out.close();
  32. if(unpackFile.endsWith(".rar") || unpackFile.endsWith(".zip")){ //子文件下还有被压缩的文件
  33. UnPackage.unPackagedFile(unpackFile,unpackFile.substring(0,unpackFile.lastIndexOf(File.separator)));
  34. }
  35. }
  36. zip.close();
  37. }catch (Exception e){
  38. logger.error("Zip decompressFile异常");
  39. return false;
  40. }
  41. return true;
  42. }
  43. }

学习Java的同学注意了!!!
学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入Java学习交流群,群号码:543120397 我们一起学Java!

发表评论

表情:
评论列表 (有 0 条评论,91人围观)

还没有评论,来说两句吧...

相关阅读

    相关 DXT纹理压缩格式

    我们知道游戏中对于3D物体表面细节的表现最重要的还是靠贴图来实现的,那么越是高分辨率越是真彩色的贴图自然表现力也是越强,