当前位置:   article > 正文

对rar文件的解压缩,对zip文件的压缩与解压缩_com/github/junrar/archive

com/github/junrar/archive

 

一、对rar文件的解压缩

1、maven

  1. <dependency>
  2.             <groupId>com.github.junrar</groupId>
  3.             <artifactId>junrar</artifactId>
  4.             <version>0.7</version>
  5.        </dependency>

2、解压类

  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.util.regex.Matcher;
  4. import java.util.regex.Pattern;
  5. import com.github.junrar.Archive;
  6. import com.github.junrar.rarfile.FileHeader;
  7. /**
  8. * rar的解压
  9. */
  10. public class UnRar {
  11. /**
  12. *
  13. * @param srcRarPath rar文件完整路径
  14. * @param dstDirectoryPath 解压到的文件夹
  15. */
  16. public static void unrar(String srcRarPath,String dstDirectoryPath){
  17. if (!srcRarPath.toLowerCase().endsWith(".rar")) {
  18. /**
  19. * 抛出异常
  20. */
  21. System.out.println("非rar文件!");
  22. return;
  23. }
  24. File dstDiretory = new File(dstDirectoryPath);
  25. if (!dstDiretory.exists()) {// 目标目录不存在时,创建该文件夹
  26. dstDiretory.mkdirs();
  27. }
  28. File fol=null,out=null;
  29. Archive a = null;
  30. try {
  31. a = new Archive(new File(srcRarPath));
  32. if (a != null){
  33. //a.getMainHeader().print(); // 打印文件信息.
  34. FileHeader fh = a.nextFileHeader();
  35. while (fh != null){
  36. if (fh.isDirectory()) { // 文件夹
  37. // 如果是中文路径,调用getFileNameW()方法,否则调用getFileNameString()方法,还可以使用if(fh.isUnicode())
  38. if(existZH(fh.getFileNameW())){
  39. fol = new File(dstDirectoryPath + File.separator
  40. + fh.getFileNameW());
  41. }else{
  42. fol = new File(dstDirectoryPath + File.separator
  43. + fh.getFileNameString());
  44. }
  45. fol.mkdirs();
  46. } else { // 文件
  47. if(existZH(fh.getFileNameW())){
  48. out = new File(dstDirectoryPath + File.separator
  49. + fh.getFileNameW().trim());
  50. }else{
  51. out = new File(dstDirectoryPath + File.separator
  52. + fh.getFileNameString().trim());
  53. }
  54. try {// 之所以这么写try,是因为万一这里面有了异常,不影响继续解压.
  55. if (!out.exists()) {
  56. if (!out.getParentFile().exists()){// 相对路径可能多级,可能需要创建父目录.
  57. out.getParentFile().mkdirs();
  58. }
  59. out.createNewFile();
  60. }
  61. FileOutputStream os = new FileOutputStream(out);
  62. a.extractFile(fh, os);
  63. os.close();
  64. } catch (Exception ex) {
  65. ex.printStackTrace();
  66. }
  67. }
  68. fh = a.nextFileHeader();
  69. }
  70. a.close();
  71. }
  72. } catch (Exception e){
  73. e.printStackTrace();
  74. }
  75. }
  76. /**
  77. * 判断是否中文
  78. * @param str
  79. * @return
  80. */
  81. public static boolean existZH(String str){
  82. String regEx = "[\\u4e00-\\u9fa5]";
  83. Pattern p = Pattern.compile(regEx);
  84. Matcher m = p.matcher(str);
  85. while (m.find()) {
  86. return true;
  87. }
  88. return false;
  89. }
  90. }

 

2、对zip文件的压缩与解压缩

  1. import java.io.*;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.zip.ZipEntry;
  5. import java.util.zip.ZipInputStream;
  6. import java.util.zip.ZipOutputStream;
  7. /**
  8. * Zip压缩/解压缩工具类
  9. * 实现对目标路径及其子路径下的所有文件及空目录的压缩
  10. * 参考网上若干种实现,并修改其bug
  11. *
  12. * @version v0.1, 17/09/04
  13. * @author Kiwi Liu
  14. */
  15. public class ZipUtil {
  16. /** 缓冲器大小 */
  17. private static final int BUFFER = 512;
  18. /**
  19. * 取的给定源目录下的所有文件及空的子目录
  20. * 递归实现
  21. *
  22. * @param srcFile
  23. *
  24. * @return
  25. */
  26. private static List<File> getAllFiles(File srcFile) {
  27. List<File> fileList = new ArrayList<File>();
  28. File[] tmp = srcFile.listFiles();
  29. for (int i = 0; i < tmp.length; i++) {
  30. if (tmp[i].isFile()) {
  31. fileList.add(tmp[i]);
  32. System.out.println("add file: "+tmp[i].getName());
  33. }
  34. if (tmp[i].isDirectory()) {
  35. if (tmp[i].listFiles().length!=0){//若不是空目录,则递归添加其下的目录和文件
  36. fileList.addAll(getAllFiles(tmp[i]));
  37. }
  38. else{//若是空目录,则添加这个目录到fileList
  39. fileList.add(tmp[i]);
  40. System.out.println("add empty dir: "+tmp[i].getName());
  41. }
  42. }
  43. } // end for
  44. return fileList;
  45. }
  46. /**
  47. * 取相对路径
  48. * 依据文件名和压缩源路径得到文件在压缩源路径下的相对路径
  49. *
  50. * @param dirPath 压缩源路径
  51. * @param file
  52. *
  53. * @return 相对路径
  54. */
  55. private static String getRelativePath(String dirPath, File file) {
  56. File dir = new File(dirPath);
  57. String relativePath = file.getName();
  58. while (true) {
  59. file = file.getParentFile();
  60. if (file == null) {
  61. break;
  62. }
  63. if (file.equals(dir)) {
  64. break;
  65. } else {
  66. relativePath = file.getName() + "/" + relativePath;
  67. }
  68. } // end while
  69. return relativePath;
  70. }
  71. /**
  72. * 创建文件
  73. * 根据压缩包内文件名和解压缩目的路径,创建解压缩目标文件,
  74. * 生成中间目录
  75. * @param dstPath 解压缩目的路径
  76. * @param fileName 压缩包内文件名
  77. *
  78. * @return 解压缩目标文件
  79. *
  80. * @throws IOException
  81. */
  82. private static File createFile(String dstPath, String fileName) throws IOException {
  83. String[] dirs = fileName.split("/");//将文件名的各级目录分解
  84. File file = new File(dstPath);
  85. if (dirs.length > 1) {//文件有上级目录
  86. for (int i = 0; i < dirs.length - 1; i++) {
  87. file = new File(file, dirs[i]);//依次创建文件对象知道文件的上一级目录
  88. }
  89. if (!file.exists()) {
  90. file.mkdirs();//文件对应目录若不存在,则创建
  91. System.out.println("mkdirs: " + file.getCanonicalPath());
  92. }
  93. file = new File(file, dirs[dirs.length - 1]);//创建文件
  94. return file;
  95. } else {
  96. if (!file.exists()) {
  97. file.mkdirs();//若目标路径的目录不存在,则创建
  98. System.out.println("mkdirs: " + file.getCanonicalPath());
  99. }
  100. file = new File(file, dirs[0]);//创建文件
  101. return file;
  102. }
  103. }
  104. /**
  105. * 解压缩方法
  106. *
  107. *
  108. * @param zipFileName 压缩文件名
  109. * @param dstPath 解压目标路径
  110. *
  111. * @return
  112. */
  113. public static boolean unzip(String zipFileName, String dstPath) {
  114. System.out.println("zip uncompressing...");
  115. try {
  116. ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFileName));
  117. ZipEntry zipEntry = null;
  118. byte[] buffer = new byte[BUFFER];//缓冲器
  119. int readLength = 0;//每次读出来的长度
  120. //System.out.println(zipInputStream.getNextEntry().getName());
  121. while ((zipEntry = zipInputStream.getNextEntry()) != null) {
  122. if (zipEntry.isDirectory()) {//若是zip条目目录,则需创建这个目录
  123. File dir = new File(dstPath + "/" + zipEntry.getName());
  124. if (!dir.exists()) {
  125. dir.mkdirs();
  126. System.out.println("mkdirs: " + dir.getCanonicalPath());
  127. continue;//跳出
  128. }
  129. }
  130. File file = createFile(dstPath, zipEntry.getName());//若是文件,则需创建该文件
  131. System.out.println("file created: " + file.getCanonicalPath());
  132. OutputStream outputStream = new FileOutputStream(file);
  133. while ((readLength = zipInputStream.read(buffer, 0, BUFFER)) != -1) {
  134. outputStream.write(buffer, 0, readLength);
  135. }
  136. outputStream.close();
  137. System.out.println("file uncompressed: " + file.getCanonicalPath());
  138. } // end while
  139. } catch (FileNotFoundException e) {
  140. System.out.println(e.getMessage());
  141. e.printStackTrace();
  142. System.out.println("unzip fail!");
  143. return false;
  144. } catch (IOException e) {
  145. System.out.println(e.getMessage());
  146. e.printStackTrace();
  147. System.out.println("unzip fail!");
  148. return false;
  149. }
  150. System.out.println("unzip success!");
  151. return true;
  152. }
  153. /**
  154. * 压缩方法
  155. * (可以压缩空的子目录)
  156. * @param srcPath 压缩源路径
  157. * @param zipFileName 目标压缩文件
  158. *
  159. * @return
  160. */
  161. public static boolean zip(String srcPath, String zipFileName) {
  162. System.out.println("zip compressing...");
  163. File srcFile = new File(srcPath);
  164. List<File> fileList = getAllFiles(srcFile);//所有要压缩的文件
  165. byte[] buffer = new byte[BUFFER];//缓冲器
  166. ZipEntry zipEntry = null;
  167. int readLength = 0;//每次读出来的长度
  168. try {
  169. ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
  170. for (File file : fileList) {
  171. if (file.isFile()){//若是文件,则压缩这个文件
  172. System.out.println("file==============="+getRelativePath(srcPath, file));
  173. zipEntry = new ZipEntry(getRelativePath(srcPath, file));
  174. zipEntry.setSize(file.length());
  175. zipEntry.setTime(file.lastModified());
  176. zipOutputStream.putNextEntry(zipEntry);
  177. InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
  178. while ((readLength = inputStream.read(buffer, 0, BUFFER)) != -1) {
  179. zipOutputStream.write(buffer, 0, readLength);
  180. }
  181. inputStream.close();
  182. // System.out.println("file compressed: " + file.getCanonicalPath());
  183. }else {//若是目录(即空目录)则将这个目录写入zip条目
  184. System.out.println("dic==============="+getRelativePath(srcPath, file));
  185. zipEntry = new ZipEntry(getRelativePath(srcPath, file)+"/");
  186. zipOutputStream.putNextEntry(zipEntry);
  187. // System.out.println("dir compressed: " + file.getCanonicalPath()+"/");
  188. }
  189. } // end for
  190. zipOutputStream.close();
  191. } catch (FileNotFoundException e) {
  192. System.out.println(e.getMessage());
  193. e.printStackTrace();
  194. System.out.println("zip fail!");
  195. return false;
  196. } catch (IOException e) {
  197. System.out.println(e.getMessage());
  198. e.printStackTrace();
  199. System.out.println("zip fail!");
  200. return false;
  201. }
  202. System.out.println("zip success!");
  203. return true;
  204. }
  205. /**
  206. *
  207. * @param fileList 需要压缩的文件list
  208. * @param zipFileName 压缩文件的路径加名字
  209. * @return
  210. */
  211. public static boolean zip2(List<File> fileList,String zipFileName) {
  212. System.out.println("zip compressing...");
  213. byte[] buffer = new byte[BUFFER];//缓冲器
  214. ZipEntry zipEntry = null;
  215. int readLength = 0;//每次读出来的长度
  216. try {
  217. ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
  218. for (File file : fileList) {
  219. if (file.isFile()){//若是文件,则压缩这个文件
  220. zipEntry = new ZipEntry(file.getName());
  221. zipEntry.setSize(file.length());
  222. zipEntry.setTime(file.lastModified());
  223. zipOutputStream.putNextEntry(zipEntry);
  224. InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
  225. while ((readLength = inputStream.read(buffer, 0, BUFFER)) != -1) {
  226. zipOutputStream.write(buffer, 0, readLength);
  227. }
  228. inputStream.close();
  229. System.out.println("file compressed: " + file.getCanonicalPath());
  230. }else {//若是目录(即空目录)则将这个目录写入zip条目
  231. zipEntry = new ZipEntry(file.getName()+"/");
  232. zipOutputStream.putNextEntry(zipEntry);
  233. System.out.println("dir compressed: " + file.getCanonicalPath()+"/");
  234. }
  235. } // end for
  236. zipOutputStream.close();
  237. } catch (FileNotFoundException e) {
  238. e.printStackTrace();
  239. return false;
  240. } catch (IOException e) {
  241. e.printStackTrace();
  242. return false;
  243. }
  244. System.out.println("zip success!");
  245. return true;
  246. }
  247. }

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/388093
推荐阅读
相关标签
  

闽ICP备14008679号