文件打包(.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,将这三个文件打包 ...
随机推荐
- BZOJ3932[CQOI2015]任务查询系统——主席树
题目描述 最近实验室正在为其管理的超级计算机编制一套任务管理系统,而你被安排完成其中的查询部分.超级计算机中的 任务用三元组(Si,Ei,Pi)描述,(Si,Ei,Pi)表示任务从第Si秒开始,在第E ...
- echarts之简单的入门——【二】再增加一个柱状图和图例组件
echarts之简单的入门——[一]做个带时间轴的柱状统计图 现在需求说,我需要知道日答题总次数和活跃人数,那么我们如何在上面的图表中增加一个柱状图呢? 如果你看过简单入门中的配置项手册中series ...
- webapi返回泛型给easyui
由于之前遇到的easyui调用webapi的问题. 参见 :http://blog.csdn.net/hanjun0612/article/details/51144991 所以就考虑,封装一个泛型用 ...
- openfalcon架构及相关服务配置详解
一:openfalcon组件 1.falcon-agent 数据采集组件 agent内置了一个http接口,会自动采集预先定义的各种采集项,每隔60秒,push到transfer. 2.transfe ...
- ROADS POJ - 1724(分层最短路)
就是在最短路的基础上 多加了一个时间的限制 , 多一个限制多一维就好了 记住 分层最短路要用dijistra !!! #include <iostream> #include < ...
- POJ - 3159(Candies)差分约束
题意: 就是分糖果 然后A觉得B比他优秀 所以分的糖果可以比他多 但最多不能超过c1个, B又觉得A比他优秀.... 符合差分约束的条件 设A分了x个 B分了y个 则x-y <= c1 , ...
- luogu P2644 树上游戏
一道点分难题 首先很自然的想法就是每种颜色的贡献可以分开计算,然后如果你会虚树就可以直接做了 点分也差不多,考虑每个分治重心的子树对它的贡献以及它对它子树的贡献 首先,处理一个\(cnt\)数组,\( ...
- Gym 100971J-Robots at Warehouse
题目链接:http://codeforces.com/gym/100971/problem/J Vitaly works at the warehouse. The warehouse can be ...
- Azure vm 扩展脚本自动部署Elasticsearch集群
一.完整过程比较长,我仅给出Azure vm extension script 一键部署Elasticsearch集群的安装脚本,有需要的同学,可以邮件我,我给你完整的ARM Template 如果你 ...
- Xshell配置是vi显示多种颜色
在链接中,点 File菜单——properties 或按快捷键 alt+p 第一步: Properties--->Terminal 右边的窗口中,将Terminal Type 选择为linu ...