当前位置:   article > 正文

Java压缩zip文件(怎样用Java将文件追加到zip文件)_java spring boot 7z压缩包追加文件

java spring boot 7z压缩包追加文件

学习Java压缩zip文件:

  1. 压缩单个文件和多个文件,不包含文件夹;
  2. 怎样用Java将文件追加到zip文件中。

测试类:

  1. /**
  2. * @FileName:ZipTest.java
  3. * @Description: TODO
  4. * @Copyright: All rights Reserved, Designed By [meter] Copyright(C) 2010-2018
  5. * @Company:
  6. * @author:meter
  7. * @version: V1.0
  8. * @Create:2018年5月4日 上午9:50:22
  9. *
  10. * Modification History:
  11. * Date Author Version Discription
  12. * -----------------------------------------------------------------------------------
  13. * 2018年5月4日 meter 1.0 1.0
  14. * Why & What is modified: <修改原因描述>
  15. */
  16. package org.meter.demo;
  17. import java.io.File;
  18. import java.io.FileFilter;
  19. import java.text.SimpleDateFormat;
  20. import java.util.ArrayList;
  21. import java.util.Date;
  22. import java.util.List;
  23. import java.util.Scanner;
  24. import java.util.concurrent.LinkedBlockingQueue;
  25. import java.util.concurrent.ThreadPoolExecutor;
  26. import java.util.concurrent.TimeUnit;
  27. import org.meter.zip.ZipTools;
  28. /**
  29. * @项目名称:meter
  30. * @类名称:ZipTest
  31. * @类描述:
  32. * @创建人:meter
  33. * @创建时间:2018年5月4日 上午9:50:22
  34. * @版权:Copyright@2018.All Rights Reserved
  35. * @version v1.0
  36. */
  37. public class ZipTest {
  38. private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSSS");
  39. private static ThreadPoolExecutor workerPool=new ThreadPoolExecutor(20,
  40. 25,
  41. 1,
  42. TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(15),
  43. new ThreadPoolExecutor.CallerRunsPolicy());
  44. private static void test(String path,Long size) throws Exception{
  45. workerPool.allowCoreThreadTimeOut(true);// 设置超时时关闭线程
  46. File dir=new File(path);
  47. if(!dir.exists()){
  48. System.out.println("当前路径:"+path+"不存在");
  49. return;
  50. }
  51. System.out.println("当前路径:"+dir.getAbsolutePath());
  52. File[] files =dir.listFiles(new FileFilter(){
  53. @Override
  54. public boolean accept(File pathname) {
  55. if(pathname.getName().toLowerCase().endsWith(".zip")&&pathname.getName().toLowerCase().contains("sca_2018")){
  56. return true;
  57. }
  58. return false;
  59. }
  60. });
  61. long fileSize=0;
  62. List<File> fileList=new ArrayList<File>();
  63. String zipName="sca_"+sdf.format(new Date())+".zip";
  64. int flag=files.length;
  65. for(File file:files){
  66. System.out.println("读取到文件:"+file.getName());
  67. fileSize+=file.length();
  68. fileList.add(file);
  69. flag--;
  70. if(fileSize>=size){
  71. workerPool.execute(new InnerWorker(fileList,zipName));
  72. fileSize=0;
  73. fileList=new ArrayList<File>();
  74. zipName="sca_"+sdf.format(new Date())+".zip";
  75. } else if(flag<=0){
  76. ZipTools.zipFiles(fileList,new File(zipName));
  77. }
  78. }
  79. }
  80. private static class InnerWorker implements Runnable{
  81. private List<File> fileList;
  82. private String zipName;
  83. public InnerWorker(List<File> fileList,String zipName){
  84. this.fileList=fileList;
  85. this.zipName=zipName;
  86. }
  87. @Override
  88. public void run() {
  89. try {
  90. ZipTools.zipFiles(fileList,new File(zipName));
  91. System.out.println("压缩文件["+zipName+"]成功。");
  92. } catch (Exception e) {
  93. e.printStackTrace();
  94. System.out.println("压缩失败文件:"+zipName);
  95. }
  96. }
  97. }
  98. /** @创建日期:2018年5月4日 上午9:50:22
  99. * @作者: meter
  100. * @描述:TODO
  101. * @Title: main
  102. * @param args
  103. * @throws Exception
  104. */
  105. public static void main(String[] args) throws Exception {
  106. System.out.println("Please input the path:");
  107. Scanner input = new Scanner(System.in);
  108. String path=input.nextLine();
  109. test(path,2147483648L);
  110. }
  111. }

工具类:

  1. /**
  2. * @FileName:ZipTools.java
  3. * @Description: TODO
  4. * @Copyright: All rights Reserved, Designed By [meter] Copyright(C) 2010-2018
  5. * @Company: 米特娱乐乐园
  6. * @author:meter
  7. * @version: V1.0
  8. * @Create:2018年5月4日 上午10:25:09
  9. *
  10. * Modification History:
  11. * Date Author Version Discription
  12. * -----------------------------------------------------------------------------------
  13. * 2018年5月4日 meter 1.0 1.0
  14. * Why & What is modified: <修改原因描述>
  15. */
  16. package org.meter.zip;
  17. import java.io.BufferedInputStream;
  18. import java.io.BufferedOutputStream;
  19. import java.io.File;
  20. import java.io.FileInputStream;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import java.io.OutputStream;
  25. import java.nio.charset.Charset;
  26. import java.util.Enumeration;
  27. import java.util.List;
  28. import java.util.zip.ZipEntry;
  29. import java.util.zip.ZipFile;
  30. import java.util.zip.ZipOutputStream;
  31. /**
  32. * @项目名称:meter
  33. * @类名称:ZipTools
  34. * @类描述:采用zip压缩文件
  35. * @创建人:meter
  36. * @创建时间:2018年5月4日 上午10:25:09
  37. * @版权:Copyright@2018.All Rights Reserved
  38. * @version v1.0
  39. */
  40. public class ZipTools {
  41. /**
  42. * @创建日期:2018年5月4日 下午1:37:22
  43. * @作者: meter
  44. * @描述:压缩多个文件的情况
  45. * @Title: zip
  46. * @param fileList
  47. * @param zipFile
  48. * @throws Exception
  49. */
  50. public static void zipFiles(List<File> fileList,File zipFile) throws Exception{
  51. System.out.println("zipFiles待压缩文件:"+zipFile.getAbsolutePath());
  52. if(fileList != null){
  53. if(zipFile.exists()){//压缩文件已经存在,则只能单个添加
  54. for(File file:fileList){
  55. zip(zipFile,file);
  56. }
  57. }else{//不存在则新建
  58. // 创建zip输出流
  59. ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(zipFile), Charset.forName("UTF-8"));
  60. // 创建缓冲输出流
  61. BufferedOutputStream bufferOutStream = new BufferedOutputStream(zipOutStream);
  62. for(File file:fileList){
  63. zipFile(file,zipOutStream,bufferOutStream);
  64. }
  65. //最后关闭输出流
  66. bufferOutStream.close();
  67. zipOutStream.close();
  68. }
  69. }
  70. }
  71. /**
  72. * @创建日期:2018年5月4日 下午1:44:55
  73. * @作者: meter
  74. * @描述:执行文件压缩
  75. * @Title: zipFile
  76. * @param file
  77. * @param zipOutStream
  78. * @param bufferOutStream
  79. * @throws IOException
  80. */
  81. private static void zipFile(File file,ZipOutputStream zipOutStream,BufferedOutputStream bufferOutStream) throws IOException{
  82. // 创建压缩文件实体
  83. ZipEntry entry = new ZipEntry(file.getName());
  84. // 添加实体
  85. zipOutStream.putNextEntry(entry);
  86. // 创建输入流
  87. BufferedInputStream bufferInputStream = new BufferedInputStream(new FileInputStream(file));
  88. write(bufferInputStream, bufferOutStream);
  89. zipOutStream.closeEntry();
  90. }
  91. /**
  92. * @创建日期:2018年5月4日 下午1:37:01
  93. * @作者: meter
  94. * @描述:压缩单个文件
  95. * @Title: zip
  96. * @param zipFile
  97. * @param sourceFile
  98. * @throws Exception
  99. */
  100. public static void zip(File zipFile, File sourceFile) throws Exception {
  101. System.out.println("待压缩文件:"+zipFile.getAbsolutePath());
  102. if (zipFile.exists()) {// 添加到已经存在的压缩文件中
  103. File tempFile=new File(zipFile.getAbsolutePath()+".tmp");
  104. // 创建zip输出流
  105. ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(tempFile), Charset.forName("UTF-8"));
  106. // 创建缓冲输出流
  107. BufferedOutputStream bufferOutStream = new BufferedOutputStream(zipOutStream);
  108. ZipFile zipOutFile = new ZipFile(zipFile);
  109. Enumeration<? extends ZipEntry> entries = zipOutFile.entries();
  110. while (entries.hasMoreElements()) {
  111. ZipEntry entry = entries.nextElement();
  112. System.out.println("copy: " + entry.getName());
  113. zipOutStream.putNextEntry(entry);
  114. if (!entry.isDirectory()) {
  115. write(zipOutFile.getInputStream(entry), bufferOutStream);
  116. }
  117. zipOutStream.closeEntry();
  118. }
  119. zipOutFile.close();//记得关闭zip文件,否则后面无法删除原始文件
  120. ZipEntry entry = new ZipEntry(sourceFile.getName());
  121. // 添加实体
  122. zipOutStream.putNextEntry(entry);
  123. BufferedInputStream bufferInputStream = new BufferedInputStream(new FileInputStream(sourceFile));
  124. write(bufferInputStream, bufferOutStream);
  125. //最后关闭输出流
  126. bufferOutStream.close();
  127. zipOutStream.close();
  128. boolean flag=zipFile.delete();
  129. if(flag){
  130. tempFile.renameTo(zipFile);
  131. }else{
  132. System.out.println("删除文件失败。");
  133. }
  134. } else {// 新创建压缩文件
  135. // 创建zip输出流
  136. ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(zipFile), Charset.forName("UTF-8"));
  137. // 创建缓冲输出流
  138. BufferedOutputStream bufferOutStream = new BufferedOutputStream(zipOutStream);
  139. // 创建压缩文件实体
  140. ZipEntry entry = new ZipEntry(sourceFile.getName());
  141. // 添加实体
  142. zipOutStream.putNextEntry(entry);
  143. // 创建输入流
  144. BufferedInputStream bufferInputStream = new BufferedInputStream(new FileInputStream(sourceFile));
  145. write(bufferInputStream, bufferOutStream);
  146. //最后关闭输出流
  147. bufferOutStream.close();
  148. zipOutStream.close();
  149. }
  150. }
  151. /**
  152. * @创建日期:2018年5月4日 下午2:09:37
  153. * @作者: meter
  154. * @描述:读写zip文件
  155. * @Title: write
  156. * @param inputStream
  157. * @param outStream
  158. * @throws IOException
  159. */
  160. private static void write(InputStream inputStream,OutputStream outStream) throws IOException{
  161. byte[] data=new byte[4096];
  162. int length=0;
  163. while((length=inputStream.read(data)) != -1){
  164. outStream.write(data,0,length);
  165. }
  166. outStream.flush();//刷新输出流
  167. inputStream.close();//关闭输入流
  168. }
  169. /**
  170. * @创建日期:2018年5月4日 下午3:07:55
  171. * @作者: meter
  172. * @描述:压缩指定目录下所有文件
  173. * @Title: zipDirectory
  174. * @param dirFile
  175. * @param zipFile
  176. * @throws IOException
  177. */
  178. public static void zipDirectory(File dirFile,File zipFile) throws IOException{
  179. if(dirFile != null && dirFile.isDirectory()){
  180. if(zipFile == null){
  181. zipFile=new File(dirFile.getAbsolutePath()+".zip");
  182. }
  183. String dirName=dirFile.getName()+File.separator;
  184. // 创建zip输出流
  185. ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(zipFile), Charset.forName("UTF-8"));
  186. // 创建缓冲输出流
  187. BufferedOutputStream bufferOutStream = new BufferedOutputStream(zipOutStream);
  188. dealDirFile( dirFile,dirName,bufferOutStream,zipOutStream);
  189. //最后关闭输出流
  190. bufferOutStream.close();
  191. zipOutStream.close();
  192. }else{
  193. System.out.println("["+dirFile.getName()+"]不是一个文件夹,或者不存在。");
  194. }
  195. }
  196. /**
  197. * @创建日期:2018年5月4日 下午4:38:46
  198. * @作者: meter
  199. * @描述:处理目录文件
  200. * @Title: dealDirFile
  201. * @param dirFile
  202. * @param parentDir
  203. * @param bufferOutStream
  204. * @param zipOutStream
  205. * @throws IOException
  206. */
  207. private static void dealDirFile(File dirFile,String parentDir, BufferedOutputStream bufferOutStream, ZipOutputStream zipOutStream) throws IOException{
  208. File[] fileList=dirFile.listFiles();
  209. for(File file:fileList){
  210. if(file.isFile()){
  211. // 创建压缩文件实体
  212. ZipEntry entry = new ZipEntry(parentDir+file.getName());
  213. // 添加实体
  214. zipOutStream.putNextEntry(entry);
  215. // 创建输入流
  216. BufferedInputStream bufferInputStream = new BufferedInputStream(new FileInputStream(file));
  217. write(bufferInputStream, bufferOutStream);
  218. }else{
  219. dealDirFile(file, parentDir+file.getName()+File.separator, bufferOutStream, zipOutStream);
  220. }
  221. }
  222. }
  223. /**
  224. * @创建日期:2018年5月4日 下午3:22:11
  225. * @作者: meter
  226. * @描述:重载zipDirectory
  227. * @Title: zipDirectory
  228. * @param dirPath
  229. * @param zipPath
  230. * @throws IOException
  231. */
  232. public static void zipDirectory(String dirPath,String zipPath) throws IOException{
  233. if(zipPath==null || "".equals(zipPath)){
  234. zipDirectory(new File(dirPath),null);
  235. }else{
  236. zipDirectory(new File(dirPath),new File(zipPath));
  237. }
  238. }
  239. //------------------------------------------------米特华丽的分割线----------------------------------------------------------------------------------------
  240. /**
  241. * @创建日期:2018年5月4日 下午4:00:41
  242. * @作者: meter
  243. * @描述:解压文件
  244. * @Title: unzip
  245. * @param zipFile
  246. * @param destDir
  247. * @throws IOException
  248. */
  249. public static void unzip(File zipFile, File destDir) throws IOException {
  250. ZipFile zipOutFile = new ZipFile(zipFile,Charset.forName("gbk"));
  251. Enumeration<? extends ZipEntry> entries = zipOutFile.entries();
  252. while (entries.hasMoreElements()) {
  253. ZipEntry entry = entries.nextElement();
  254. if(entry.isDirectory()){
  255. File tempFile = new File(destDir.getAbsolutePath()+File.separator+entry.getName());
  256. if (!tempFile.exists()) {
  257. tempFile.mkdirs();
  258. }
  259. }else{
  260. File tempFile=new File(destDir.getAbsolutePath()+File.separator+entry.getName());
  261. checkParentDir(tempFile);
  262. FileOutputStream fileOutStream=new FileOutputStream(tempFile);
  263. BufferedOutputStream bufferOutStream = new BufferedOutputStream(fileOutStream);
  264. write(zipOutFile.getInputStream(entry),bufferOutStream);
  265. bufferOutStream.close();
  266. fileOutStream.close();
  267. }
  268. }
  269. zipOutFile.close();//记得关闭zip文件
  270. }
  271. /**
  272. * @创建日期:2018年5月4日 下午4:37:41
  273. * @作者: meter
  274. * @描述:验证父目录是否存在,否则创建
  275. * @Title: checkParentDir
  276. * @param file
  277. */
  278. private static void checkParentDir(File file){
  279. if(!file.getParentFile().exists()){
  280. file.getParentFile().mkdirs();
  281. }
  282. }
  283. }


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

闽ICP备14008679号