文件打包(.zip)并返回打压缩包存放路径
1.由于公司需要将一个或多个视频进行打包,格式如下图:

2.创建zipUtil工具包:
package com.seegot.util; import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand; /**
* 解压缩zip包处理类
*
*/ public class ZipUtil { private static final String ENCODE = "UTF-8"; public static void main(String[] args) throws Exception { /*ZipUtil.toZip("D:\\downAndLoad\\upload\\03674540cea94873a1e6b90a8df9f87f",
"D:\\downAndLoad\\zip\\temp","2222.zip");*/
ZipUtil.unZip("E:\\unZip1.zip", "E:\\");
} /**
* @desc 将源文件/文件夹生成指定格式的压缩文件,格式zip
* @param resourePath 源文件/文件夹
* @param targetPath 目的压缩文件保存路径
* 压缩到的位置,如果为null或空字符串则默认解压缩到跟源文件夹或者文件所在的同一目录
* @return void
*
* @throws Exception
*/
public static String toZip(String resourcesPath, String targetPath, String targetName)
throws Exception {
File resourcesFile = new File(resourcesPath); // 源文件
String directoryPath = ""; // 如果为null或空字符串则默认为目标文件夹名
if (targetName == null || targetName.trim().length() == 0)
targetName = resourcesFile.getName() + ".zip"; // 目的压缩文件名
// 如果为null或空字符串则默认解压缩到跟源文件夹或者文件所在的同一目录
// if (StringUtil.isEmpty(targetPath))
if (targetPath == null || targetPath.trim().length() == 0)
directoryPath = resourcesPath.substring(0, resourcesPath
.replaceAll("\\*", "/").lastIndexOf("\\"));
else
directoryPath = targetPath;
File targetFile = new File(directoryPath); // 目的
// 如果目的路径不存在,则新建
if (!targetFile.exists()) {
targetFile.mkdirs();
} FileOutputStream outputStream = new FileOutputStream(targetPath
+ File.separator + targetName);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
outputStream));
createCompressedFile(out, resourcesFile, "");
out.close();
return targetPath+"\\"+targetName;
} /**
* @desc 生成压缩文件。 如果是文件夹,则使用递归,进行文件遍历、压缩
* 如果是文件,直接压缩
* @param out 输出流
* @param file 目标文件
* @return void
* @throws Exception
*/
public static void createCompressedFile(ZipOutputStream out, File file,
String dir) throws Exception {
InputStream is = null;
try{
// 如果当前的是文件夹,则进行进一步处理
if (file.isDirectory()) {
// 得到文件列表信息
File[] files = file.listFiles();
// 将文件夹添加到下一级打包目录
out.putNextEntry(new ZipEntry(dir + "/"));
dir = dir.length() == 0 ? "" : dir + "/";
// 循环将文件夹中的文件打包
for (int i = 0; i < files.length; i++) {
createCompressedFile(out, files[i], dir + files[i].getName()); // 递归处理
}
} else { // 当前的是文件,打包处理
// 文件输入流
is = new FileInputStream(file);
out.putNextEntry(new ZipEntry(dir));
// 进行写操作
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
// 关闭输入流
is.close();
}
}catch (Exception e) {
is.close();
out.close();
}
} /****
* 解压
*
* @param zipPath
* zip文件路径
* @param destinationPath
* 解压的目的地点
* @param ecode
* 文件名的编码字符集
*/
public static void unZip(String zipPath, String destinationPath) {
File zipFile = new File(zipPath);
if (!zipFile.exists())
throw new RuntimeException("zip file " + zipPath
+ " does not exist.");
Project proj = new Project();
Expand expand = new Expand();
expand.setProject(proj);
expand.setTaskType("unzip");
expand.setTaskName("unzip");
expand.setSrc(zipFile);
expand.setDest(new File(destinationPath));
expand.setEncoding(ENCODE);
expand.execute();
System.out.println("unzip done!!!");
} // /**
// * 解压缩zip包
// *
// * @param zipFilePath zip文件路径
// * @param targetPath 解压缩到的位置,如果为null或空字符串则默认解压缩到跟zip包同目录跟zip包同名的文件夹下
// * @throws IOException
// *
// */
// public static void unZip(String zipFilePath, String targetPath)
// throws IOException {
// ZipFile zipFile = new ZipFile(zipFilePath);
// String directoryPath = "";
// // 如果为null或空字符串则默认解压缩到跟zip包同目录跟zip包同名的文件夹下
// // if (StringUtil.isEmpty(targetPath))
// if (targetPath == null || targetPath.trim().length() == 0)
// directoryPath = zipFilePath.substring(0,
// zipFilePath.lastIndexOf("."));
// else
// directoryPath = targetPath;
//
// Enumeration<ZipEntry> entryEnum = zipFile.getEntries();
// OutputStream os = null;
// InputStream is = null;
// try{
// if (entryEnum != null) {
// ZipEntry zipEntry = null;
// while (entryEnum.hasMoreElements()) {
// zipEntry = (ZipEntry) entryEnum.nextElement();
// // 如果为目录
// if (zipEntry.isDirectory()) {
// System.out.println("文件夹路径--------------" + directoryPath
// + File.separator + zipEntry.getName());
// File target = new File(directoryPath + File.separator
// + zipEntry.getName());
// target.mkdirs();
// continue;
// }
// if (zipEntry.getSize() != -1) {
// // 文件
// File targetFile = new File(directoryPath + File.separator
// + zipEntry.getName());
// // 如果目的文件夹的父目录为空,则创建
// if (!targetFile.getParentFile().exists()) {
// targetFile.getParentFile().mkdirs();
// targetFile = new File(targetFile.getAbsolutePath());
// }
// os = new BufferedOutputStream(
// new FileOutputStream(targetFile));
// is = zipFile.getInputStream(zipEntry);
// byte[] buffer = new byte[1024];
// int len = 0;
// while ((len = is.read(buffer, 0, 1024)) >= 0) {
// os.write(buffer, 0, len);
// }
// }
// }
// }
// }finally{
// if(os!=null)
// os.close();
// if(is!=null)
// is.close();
// zipFile.close();
// }
// } }
3.编写自己的方法
String fileUrl = request.getParameter("fileUrl");
String[] fileUrls = fileUrl.split(",");
String filename = request.getParameter("filename"); // 编号-
// code = new String(code.getBytes("iso-8859-1"), "UTF-8");
String timeLength = request.getParameter("timeLength");
String[] timeLengths = timeLength.split(",");
String tempZipPath = PropertyUtil.getProperty("tempZipPath"); // 临时路径
String scormTempletPath = PropertyUtil.getProperty("scormTemplet"); // scorm样板路径 2017-06-30
String mp4path = PropertyUtil.getProperty("mp4path"); // scorm样板路径
String uuid = UUID.randomUUID().toString().replace("-", "");
String dbPath = tempZipPath + uuid + "\\" + filename + "\\";
// 判断该路径是否存在,如果不存在这创建一个这样的路径
if (!new File(dbPath).exists())
new File(dbPath).mkdirs();
// 首先复制文件夹到临时文件夹下面
copyDir(scormTempletPath, dbPath);
// 将视频文件复制到临时路径下
for (int i = 0; i < fileUrls.length; i++) {
String path = mp4path + fileUrls[i];
System.out.println("视频文件path:" + path + "------------");
copyFile(path, dbPath);// 从path 复制到dbpath
}
// 创建一个 videoList.txt
creatTxt(dbPath, fileUrls, timeLengths);
// 创建一个videoList.xml
creatXML(dbPath, fileUrls, timeLengths);
// 写入完毕后打包
SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyyMMssHHmmSSS");
String timeformat = simpleDateFormat.format(new Date());
String fileZipUrl = tempZipPath+timeformat+"\\";
ZipUtil.toZip(dbPath, fileZipUrl, filename + ".zip");
return fileZipUrl;
4.copy文件方法
/**
* @desc 复制文件夹
* @author zp
* @date 2017-2-28
* @param oldPath
* @param newPath
* @throws IOException
*/
public static void copyDir(String oldPath, String newPath)
throws IOException {
try {
(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
File a = new File(oldPath);
String[] file = a.list();
File temp = null;
for (int i = 0; i < file.length; i++) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + file[i]);
} else {
temp = new File(oldPath + File.separator + file[i]);
} if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath
+ "/" + (temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {// 如果是子文件夹
copyDir(oldPath + "/" + file[i], newPath + "/" + file[i]);
}
}
} catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace(); }
}
5.创建txt xml 看前两个随笔。
文件打包(.zip)并返回打压缩包存放路径的更多相关文章
- java 多个文件打包zip
/** * 多个文件打包成zip */ public class ZipDemo { private static void create() throws Exception{ String pat ...
- Web端文件打包.zip下载
使用ant.jar包的API进行文件夹打包.直接上代码: String zipfilename = "test.zip"; File zipfile = new File(zipf ...
- Linux文件打包与解压缩
一.文件打包和解压缩 常用的压缩包文件格式.在 Windows 上我们最常见的不外乎这三种*.zip,*.rar,*.7z后缀的压缩文件,而在 Linux 上面常见常用的除了以上这三种外,还有*.gz ...
- Node.js使用jszip实现打包zip压缩包
一.前言 最近有这样的一个需求,需要把两个同名的.mtl文件和.obj文件打包成一个同名的.zip压缩包.刚开始文件不多的时候,只有几个,或者十几个,甚至二三十个的时候,还能勉强接受手动修改,但是随着 ...
- java将文件打包成ZIP压缩文件的工具类实例
package com.lanp; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ja ...
- PHP扩展类ZipArchive实现压缩解压Zip文件和文件打包下载 && Linux下的ZipArchive配置开启压缩 &&搞个鸡巴毛,写少了个‘/’号,浪费了一天
PHP ZipArchive 是PHP自带的扩展类,可以轻松实现ZIP文件的压缩和解压,使用前首先要确保PHP ZIP 扩展已经开启,具体开启方法就不说了,不同的平台开启PHP扩增的方法网上都有,如有 ...
- PHP扩展类ZipArchive实现压缩解压Zip文件和文件打包下载
文章转载自:https://my.oschina.net/junn/blog/104464 PHP ZipArchive 是PHP自带的扩展类,可以轻松实现ZIP文件的压缩和解压,使用前首先要确保PH ...
- 使用PHP自带zlib函数 几行代码实现PHP文件打包下载zip
<?php //获取文件列表 function list_dir($dir){ $result = array(); if (is_dir($dir)){ $file_dir = scandir ...
- PHP 多文件打包下载 zip
<?php $zipname = './photo.zip'; //服务器根目录下有文件夹public,其中包含三个文件img1.jpg, img2.jpg, img3.jpg,将这三个文件打包 ...
随机推荐
- Java原子类实现原理分析
在谈谈java中的volatile一文中,我们提到过并发包中的原子类可以解决类似num++这样的复合类操作的原子性问题,相比锁机制,使用原子类更精巧轻量,性能开销更小,本章就一起来分析下原子类的实现机 ...
- 最大获利 HYSBZ - 1497 (最大权闭合图)
最大权闭合图: 有向图,每个点有点权,点权可正可负.对于任意一条有向边i和j,选择了点i就必须选择点j,你需要选择一些点使得得到权值最大. 解决方法: 网络流 对于任意点i,如果i权值为正,s向i连容 ...
- Leetcode 371.两整数之和 By Python
不使用运算符 + 和 - ,计算两整数 a .b 之和. 示例 1: 输入: a = 1, b = 2 输出: 3 示例 2: 输入: a = -2, b = 3 输出: 1 思路 比如\(5+6=1 ...
- Java 实现金额转换 代码示例
金额转换,阿拉伯数字的金额转换成中国传统的形式如: (¥1011)→(壹仟零壹拾壹元整)输出. 分析: 金额转换,在开发财务相关软件时会经常用到,也是软件本地化的一个需要.一般开发公司或者团队都有相应 ...
- 【Code Chef】April Challenge 2019
Subtree Removal 很显然不可能选择砍掉一对有祖先关系的子树.令$f_i$表示$i$子树的答案,如果$i$不被砍,那就是$a_i + \sum\limits_j f_j$:如果$i$被砍, ...
- Git中设置代理和取消代理
设置Socks5代理 git config --global http.proxy 'socks5://127.0.0.1:1080' && git config --global h ...
- C# winform C/S WebBrowser qq第三方授权登录
qq的授权登录,跟微信相似,不同的地方是: 1 申请appid与appkey的时候,注意填写回调地址. 2 这里可以在WebBrowser的是Navigated事件中直接得到Access Token, ...
- Druid 配置及内置监控,Web页面查看监控内容
1.配置Druid的内置监控 首先在Maven项目的pom.xml中引入包 <dependency> <groupId>com.alibaba</groupId> ...
- promise第一篇-简介
1. 创建一个promise对象 var promise = new Promise(function(resolve, reject){ //异步处理 //处理结束后调用resolve或reject ...
- [python网络编程]使用scapy修改源IP发送请求
Python爬虫视频教程零基础小白到scrapy爬虫高手-轻松入门 https://item.taobao.com/item.htm?spm=a1z38n.10677092.0.0.482434a6E ...