文件打包(.zip)并返回打压缩包存放路径

1.由于公司需要将一个或多个视频进行打包,格式如下图:

2.创建zipUtil工具包:

  1 package com.seegot.util;
  2 
  3 import java.io.BufferedOutputStream;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileOutputStream;
  7 import java.io.InputStream;
  8 import java.util.zip.ZipEntry;
  9 import java.util.zip.ZipOutputStream;
 10 
 11 import org.apache.tools.ant.Project;
 12 import org.apache.tools.ant.taskdefs.Expand;
 13 
 14 /**
 15  * 解压缩zip包处理类
 16  * 
 17  */
 18 
 19 public class ZipUtil {
 20     
 21     private static final String ENCODE = "UTF-8";
 22     
 23     public static void main(String[] args) throws Exception {
 24         
 25         /*ZipUtil.toZip("D:\downAndLoad\upload\03674540cea94873a1e6b90a8df9f87f", 
 26         "D:\downAndLoad\zip\temp","2222.zip");*/
 27         ZipUtil.unZip("E:\unZip1.zip", "E:\");
 28     }
 29     
 30     /**
 31     * @desc 将源文件/文件夹生成指定格式的压缩文件,格式zip
 32     * @param resourePath 源文件/文件夹
 33     * @param targetPath  目的压缩文件保存路径
 34     *                        压缩到的位置,如果为null或空字符串则默认解压缩到跟源文件夹或者文件所在的同一目录
 35     * @return void
 36     *               
 37     * @throws Exception
 38     */
 39     public static String toZip(String resourcesPath, String targetPath, String targetName)
 40             throws Exception {
 41         File resourcesFile = new File(resourcesPath); // 源文件
 42         String directoryPath = "";
 43         
 44         // 如果为null或空字符串则默认为目标文件夹名
 45         if (targetName == null || targetName.trim().length() == 0)
 46             targetName = resourcesFile.getName() + ".zip"; // 目的压缩文件名
 47         // 如果为null或空字符串则默认解压缩到跟源文件夹或者文件所在的同一目录
 48 //        if (StringUtil.isEmpty(targetPath))
 49         if (targetPath == null || targetPath.trim().length() == 0)
 50             directoryPath = resourcesPath.substring(0, resourcesPath
 51                     .replaceAll("\*", "/").lastIndexOf("\"));
 52         else
 53             directoryPath = targetPath;
 54         File targetFile = new File(directoryPath); // 目的
 55         // 如果目的路径不存在,则新建
 56         if (!targetFile.exists()) {
 57             targetFile.mkdirs();
 58         } 
 59         
 60         FileOutputStream outputStream = new FileOutputStream(targetPath
 61                 + File.separator + targetName);
 62         ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
 63                 outputStream));
 64         createCompressedFile(out, resourcesFile, "");
 65         out.close();
 66         return targetPath+"\"+targetName;
 67     }
 68     
 69     /**
 70     * @desc 生成压缩文件。 如果是文件夹,则使用递归,进行文件遍历、压缩
 71     *                     如果是文件,直接压缩
 72     * @param out  输出流
 73     * @param file  目标文件
 74     * @return void
 75     * @throws Exception
 76     */
 77     public static void createCompressedFile(ZipOutputStream out, File file,
 78             String dir) throws Exception {
 79         InputStream is = null;
 80         try{
 81             // 如果当前的是文件夹,则进行进一步处理
 82             if (file.isDirectory()) {
 83                 // 得到文件列表信息
 84                 File[] files = file.listFiles();
 85                 // 将文件夹添加到下一级打包目录
 86                 out.putNextEntry(new ZipEntry(dir + "/"));
 87                 dir = dir.length() == 0 ? "" : dir + "/";
 88                 // 循环将文件夹中的文件打包
 89                 for (int i = 0; i < files.length; i++) {
 90                     createCompressedFile(out, files[i], dir + files[i].getName()); // 递归处理
 91                 }
 92             } else { // 当前的是文件,打包处理
 93                 // 文件输入流
 94                 is = new FileInputStream(file);
 95                 out.putNextEntry(new ZipEntry(dir));
 96                 // 进行写操作
 97                 int len = 0;
 98                 byte[] buffer = new byte[1024];
 99                 while ((len = is.read(buffer)) > 0) {
100                     out.write(buffer, 0, len);
101                 }
102                 // 关闭输入流
103                 is.close();
104             }
105         }catch (Exception e) {
106             is.close();
107             out.close();
108         }
109     }
110     
111     
112     /****
113      * 解压
114      * 
115      * @param zipPath
116      *            zip文件路径
117      * @param destinationPath
118      *            解压的目的地点
119      * @param ecode
120      *            文件名的编码字符集
121      */
122     public static void unZip(String zipPath, String destinationPath) {
123         File zipFile = new File(zipPath);
124         if (!zipFile.exists())
125             throw new RuntimeException("zip file " + zipPath
126                     + " does not exist.");
127         Project proj = new Project();
128         Expand expand = new Expand();
129         expand.setProject(proj);
130         expand.setTaskType("unzip");
131         expand.setTaskName("unzip");
132         expand.setSrc(zipFile);
133         expand.setDest(new File(destinationPath));
134         expand.setEncoding(ENCODE);
135         expand.execute();
136         System.out.println("unzip done!!!");
137     }
138     
139 //    /**
140 //     * 解压缩zip包 
141 //     * 
142 //     * @param zipFilePath zip文件路径
143 //     * @param targetPath 解压缩到的位置,如果为null或空字符串则默认解压缩到跟zip包同目录跟zip包同名的文件夹下 
144 //     * @throws IOException
145 //     * 
146 //     */
147 //    public static void unZip(String zipFilePath, String targetPath)
148 //            throws IOException {
149 //        ZipFile zipFile = new ZipFile(zipFilePath);
150 //        String directoryPath = "";
151 //        // 如果为null或空字符串则默认解压缩到跟zip包同目录跟zip包同名的文件夹下
152 //        // if (StringUtil.isEmpty(targetPath))
153 //        if (targetPath == null || targetPath.trim().length() == 0)
154 //            directoryPath = zipFilePath.substring(0,
155 //                    zipFilePath.lastIndexOf("."));
156 //        else
157 //            directoryPath = targetPath;
158 //
159 //        Enumeration<ZipEntry> entryEnum = zipFile.getEntries();
160 //        OutputStream os = null;
161 //        InputStream is = null;
162 //        try{
163 //            if (entryEnum != null) {
164 //                ZipEntry zipEntry = null;
165 //                while (entryEnum.hasMoreElements()) {
166 //                    zipEntry = (ZipEntry) entryEnum.nextElement();
167 //                    // 如果为目录
168 //                    if (zipEntry.isDirectory()) {
169 //                        System.out.println("文件夹路径--------------" + directoryPath
170 //                                + File.separator + zipEntry.getName());
171 //                        File target = new File(directoryPath + File.separator
172 //                                + zipEntry.getName());
173 //                        target.mkdirs();
174 //                        continue;
175 //                    }
176 //                    if (zipEntry.getSize() != -1) {
177 //                        // 文件
178 //                        File targetFile = new File(directoryPath + File.separator
179 //                                + zipEntry.getName());
180 //                        // 如果目的文件夹的父目录为空,则创建
181 //                        if (!targetFile.getParentFile().exists()) {
182 //                            targetFile.getParentFile().mkdirs();
183 //                            targetFile = new File(targetFile.getAbsolutePath());
184 //                        }
185 //                        os = new BufferedOutputStream(
186 //                                new FileOutputStream(targetFile));
187 //                        is = zipFile.getInputStream(zipEntry);
188 //                        byte[] buffer = new byte[1024];
189 //                        int len = 0;
190 //                        while ((len = is.read(buffer, 0, 1024)) >= 0) {
191 //                            os.write(buffer, 0, len);
192 //                        }
193 //                    }
194 //                }
195 //            }
196 //        }finally{
197 //            if(os!=null)
198 //                os.close();
199 //            if(is!=null)
200 //                is.close();
201 //            zipFile.close();
202 //        }
203 //    }
204 
205 }
View Code

3.编写自己的方法

 1 String fileUrl = request.getParameter("fileUrl");
 2         String[] fileUrls = fileUrl.split(",");
 3         String filename = request.getParameter("filename"); // 编号- 
 4         // code = new String(code.getBytes("iso-8859-1"), "UTF-8");
 5         String timeLength = request.getParameter("timeLength");
 6         String[] timeLengths = timeLength.split(",");
 7         String tempZipPath = PropertyUtil.getProperty("tempZipPath"); // 临时路径
 8         String scormTempletPath = PropertyUtil.getProperty("scormTemplet"); // scorm样板路径  2017-06-30
 9         String mp4path = PropertyUtil.getProperty("mp4path"); // scorm样板路径
10         String uuid = UUID.randomUUID().toString().replace("-", "");
11         String dbPath = tempZipPath   + uuid + "\" + filename + "\"; 
12         // 判断该路径是否存在,如果不存在这创建一个这样的路径
13         if (!new File(dbPath).exists())
14             new File(dbPath).mkdirs();
15         // 首先复制文件夹到临时文件夹下面
16         copyDir(scormTempletPath, dbPath);
17         // 将视频文件复制到临时路径下
18         for (int i = 0; i < fileUrls.length; i++) {
19             String path = mp4path + fileUrls[i];
20             System.out.println("视频文件path:" + path + "------------");
21             copyFile(path, dbPath);// 从path 复制到dbpath
22         }
23         // 创建一个 videoList.txt
24         creatTxt(dbPath, fileUrls, timeLengths);
25         // 创建一个videoList.xml
26         creatXML(dbPath, fileUrls, timeLengths);
27         // 写入完毕后打包
28         SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyyMMssHHmmSSS");
29         String timeformat = simpleDateFormat.format(new Date()); 
30         String fileZipUrl = tempZipPath+timeformat+"\";
31         ZipUtil.toZip(dbPath, fileZipUrl, filename + ".zip");
32         return fileZipUrl;
View Code

 4.copy文件方法

 1     /**
 2      * @desc 复制文件夹
 3      * @author zp
 4      * @date 2017-2-28
 5      * @param oldPath
 6      * @param newPath
 7      * @throws IOException
 8      */
 9     public static void copyDir(String oldPath, String newPath)
10             throws IOException {
11         try {
12             (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
13             File a = new File(oldPath);
14             String[] file = a.list();
15             File temp = null;
16             for (int i = 0; i < file.length; i++) {
17                 if (oldPath.endsWith(File.separator)) {
18                     temp = new File(oldPath + file[i]);
19                 } else {
20                     temp = new File(oldPath + File.separator + file[i]);
21                 }
22 
23                 if (temp.isFile()) {
24                     FileInputStream input = new FileInputStream(temp);
25                     FileOutputStream output = new FileOutputStream(newPath
26                             + "/" + (temp.getName()).toString());
27                     byte[] b = new byte[1024 * 5];
28                     int len;
29                     while ((len = input.read(b)) != -1) {
30                         output.write(b, 0, len);
31                     }
32                     output.flush();
33                     output.close();
34                     input.close();
35                 }
36                 if (temp.isDirectory()) {// 如果是子文件夹
37                     copyDir(oldPath + "/" + file[i], newPath + "/" + file[i]);
38                 }
39             }
40         } catch (Exception e) {
41             System.out.println("复制整个文件夹内容操作出错");
42             e.printStackTrace();
43 
44         }
45     }
View Code

5.创建txt  xml 看前两个随笔。

原文地址:https://www.cnblogs.com/pengpengzhang/p/7262724.html