Commit 278fbfa1 by songxiang

ZIP打包下载支持分大小打包

parent bec5df1d
...@@ -9,6 +9,8 @@ package com.pcloud.common.entity; ...@@ -9,6 +9,8 @@ package com.pcloud.common.entity;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModelProperty;
/** /**
* *
* @描述: * @描述:
...@@ -107,6 +109,9 @@ public class UploadResultInfo extends BaseEntity { ...@@ -107,6 +109,9 @@ public class UploadResultInfo extends BaseEntity {
*/ */
private String m3u8Url; private String m3u8Url;
@ApiModelProperty("子文件数量")
private int fileItemCount;
public UploadResultInfo() { public UploadResultInfo() {
super(); super();
} }
...@@ -152,6 +157,14 @@ public class UploadResultInfo extends BaseEntity { ...@@ -152,6 +157,14 @@ public class UploadResultInfo extends BaseEntity {
this.url = url; this.url = url;
} }
public int getFileItemCount() {
return fileItemCount;
}
public void setFileItemCount(int fileItemCount) {
this.fileItemCount = fileItemCount;
}
public String getM3u8Url() { public String getM3u8Url() {
return m3u8Url; return m3u8Url;
} }
......
...@@ -21,6 +21,7 @@ import java.util.List; ...@@ -21,6 +21,7 @@ import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
...@@ -50,366 +51,370 @@ import it.sauronsoftware.jave.InputFormatException; ...@@ -50,366 +51,370 @@ import it.sauronsoftware.jave.InputFormatException;
*/ */
public class FileUtils { public class FileUtils {
/** /**
* logger * logger
*/ */
private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class); private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);
/** /**
* PDF * PDF
*/ */
public final static String PDF = "PDF"; public final static String PDF = "PDF";
/** /**
* XML * XML
*/ */
public final static String XML = "XML"; public final static String XML = "XML";
/** /**
* IMAGE * IMAGE
*/ */
public final static String IMAGE = "IMAGE"; public final static String IMAGE = "IMAGE";
/** /**
* 音频 * 音频
*/ */
public final static String AUDIO = "AUDIO"; public final static String AUDIO = "AUDIO";
/** /**
* 视频格式 * 视频格式
*/ */
public final static String VIDEO = "VIDEO"; public final static String VIDEO = "VIDEO";
/** /**
* 压缩格式 * 压缩格式
*/ */
public final static String COMPRESS = "COMPRESS"; public final static String COMPRESS = "COMPRESS";
/** /**
* 办公软件 * 办公软件
*/ */
public final static String EDITOR = "EDITOR"; public final static String EDITOR = "EDITOR";
/** /**
* 文本格式 * 文本格式
*/ */
public final static String TEXT = "TEXT"; public final static String TEXT = "TEXT";
/** /**
* PDF文件格式 * PDF文件格式
*/ */
public static final String[] PDF_GATHER = { "PDF" }; public static final String[] PDF_GATHER = {"PDF"};
/** /**
* XML文件格式 * XML文件格式
*/ */
public static final String[] XML_GATHER = { "XML" }; public static final String[] XML_GATHER = {"XML"};
/** /**
* 图片文件格式 * 图片文件格式
*/ */
public static final String[] IMAGE_GATHER = { "BMP", "JPG", "GIF", "PNG", "PCX", "TIF", "JPEG", "SVG" }; public static final String[] IMAGE_GATHER = {"BMP", "JPG", "GIF", "PNG", "PCX", "TIF", "JPEG", "SVG"};
/** /**
* 音頻文件格式 【"LRC" 为歌词字幕(这里作为音頻文件上传)】 * 音頻文件格式 【"LRC" 为歌词字幕(这里作为音頻文件上传)】
*/ */
public static final String[] AUDIO_GATHER = { "AMR", "MP3", "WMA", "WAV", "AAC", "APE", "M4A" }; public static final String[] AUDIO_GATHER = {"AMR", "MP3", "WMA", "WAV", "AAC", "APE", "M4A"};
/** /**
* 視頻文件格式 【"SRT", "SSA", "SMI", "SUB" 为视频“外挂型”字幕(这里作为视频文件上传)】 * 視頻文件格式 【"SRT", "SSA", "SMI", "SUB" 为视频“外挂型”字幕(这里作为视频文件上传)】
*/ */
public static final String[] VIDEO_GATHER = { "MPG", "MPEG", "AVI", "MOV", "ASF", "WMV", "NAVI", "3GP", "MKV", public static final String[] VIDEO_GATHER = {"MPG", "MPEG", "AVI", "MOV", "ASF", "WMV", "NAVI", "3GP", "MKV",
"FLV", "F4V", "RMVB", "RM", "MP4", "SRT", "SSA", "SMI", "SUB", "ASX", "M3U8" }; "FLV", "F4V", "RMVB", "RM", "MP4", "SRT", "SSA", "SMI", "SUB", "ASX", "M3U8"};
/** /**
* 压缩包文件格式 * 压缩包文件格式
*/ */
public static final String[] COMPRESS_GATHER = { "RAR", "ZIP" }; public static final String[] COMPRESS_GATHER = {"RAR", "ZIP"};
/** /**
* 文件格式 * 文件格式
*/ */
public static final String[] TEXT_GATHER = { "TXT", "LRC" }; public static final String[] TEXT_GATHER = {"TXT", "LRC"};
/** /**
* 编辑器格式 * 编辑器格式
*/ */
public static final String[] EDITOR_GATHER = { "DOC", "DOCX", "XLS", "XLSX", "PPT", "PPTX" }; public static final String[] EDITOR_GATHER = {"DOC", "DOCX", "XLS", "XLSX", "PPT", "PPTX"};
/** /**
* word格式 * word格式
*/ */
public static final String[] WORD_GATHER = { "DOC", "DOCX" }; public static final String[] WORD_GATHER = {"DOC", "DOCX"};
/** /**
* excel格式 * excel格式
*/ */
public static final String[] EXCEL_GATHER = { "XLS", "XLSX", "XLSM", "XLT", "XLTX", "XLTM", "CSV" }; public static final String[] EXCEL_GATHER = {"XLS", "XLSX", "XLSM", "XLT", "XLTX", "XLTM", "CSV"};
/** /**
* PPT格式 * PPT格式
*/ */
public static final String[] PPT_GATHER = { "PPT", "PPTX" }; public static final String[] PPT_GATHER = {"PPT", "PPTX"};
/** /**
* 根据文件类型获取文件分类 * 根据文件类型获取文件分类
* *
* @param fileType * @param fileType
* @return * @return
*/ */
public static String getGatherName(String fileType) { public static String getGatherName(String fileType) {
if (StringUtil.isEmpty(fileType)) { if (StringUtil.isEmpty(fileType)) {
return null; return null;
} }
// IMAGE // IMAGE
if (Arrays.asList(IMAGE_GATHER).contains(fileType.toUpperCase())) { if (Arrays.asList(IMAGE_GATHER).contains(fileType.toUpperCase())) {
return IMAGE; return IMAGE;
} }
// AUDIO // AUDIO
if (Arrays.asList(AUDIO_GATHER).contains(fileType.toUpperCase())) { if (Arrays.asList(AUDIO_GATHER).contains(fileType.toUpperCase())) {
return AUDIO; return AUDIO;
} }
// VIDEO // VIDEO
if (Arrays.asList(VIDEO_GATHER).contains(fileType.toUpperCase())) { if (Arrays.asList(VIDEO_GATHER).contains(fileType.toUpperCase())) {
return VIDEO; return VIDEO;
} }
// PDF // PDF
if (Arrays.asList(PDF_GATHER).contains(fileType.toUpperCase())) { if (Arrays.asList(PDF_GATHER).contains(fileType.toUpperCase())) {
return PDF; return PDF;
} }
// XML // XML
if (Arrays.asList(XML_GATHER).contains(fileType.toUpperCase())) { if (Arrays.asList(XML_GATHER).contains(fileType.toUpperCase())) {
return XML; return XML;
} }
// COMPRESS // COMPRESS
if (Arrays.asList(COMPRESS_GATHER).contains(fileType.toUpperCase())) { if (Arrays.asList(COMPRESS_GATHER).contains(fileType.toUpperCase())) {
return COMPRESS; return COMPRESS;
} }
// EDITOR // EDITOR
if (Arrays.asList(EDITOR_GATHER).contains(fileType.toUpperCase())) { if (Arrays.asList(EDITOR_GATHER).contains(fileType.toUpperCase())) {
return EDITOR; return EDITOR;
} }
// COMPRESS // COMPRESS
if (Arrays.asList(TEXT_GATHER).contains(fileType.toUpperCase())) { if (Arrays.asList(TEXT_GATHER).contains(fileType.toUpperCase())) {
return TEXT; return TEXT;
} }
return null; return null;
} }
/** /**
* 传入文件夹路径,该方法能够实现创建整个路径 * 传入文件夹路径,该方法能够实现创建整个路径
* *
* @param path * @param path 文件夹路径,不包含文件名称及后缀名
* 文件夹路径,不包含文件名称及后缀名 */
*/ public static boolean isDir(String filePath) {
public static boolean isDir(String filePath) { if (StringUtil.isEmpty(filePath)) {
if (StringUtil.isEmpty(filePath)) { return false;
return false; }
} String[] paths = filePath.split("/");
String[] paths = filePath.split("/"); String temp = "";
String temp = ""; for (int i = 0; i < paths.length; i++) {
for (int i = 0; i < paths.length; i++) { if (i == 0) {
if (i == 0) { temp = paths[0];
temp = paths[0]; } else {
} else { temp += "/" + paths[i];
temp += "/" + paths[i]; }
} creatDir(temp);
creatDir(temp); }
} return true;
return true; }
}
/**
/** * 该方法用来判断文件是否存在,如果不存在则创建
* 该方法用来判断文件是否存在,如果不存在则创建 *
* * @param filePath
* @param filePath */
*/ public static boolean creatFile(String filePath) {
public static boolean creatFile(String filePath) { if (StringUtil.isEmpty(filePath)) {
if (StringUtil.isEmpty(filePath)) { return false;
return false; }
} File file = new File(filePath);
File file = new File(filePath); if (!file.exists()) {
if (!file.exists()) { try {
try { file.createNewFile();
file.createNewFile(); return true;
return true; } catch (Exception e) {
} catch (Exception e) { LOGGER.error("【文件工具】创建文件失败,<ERROR>:" + e.getMessage(), e);
LOGGER.error("【文件工具】创建文件失败,<ERROR>:" + e.getMessage(), e); }
} }
} return false;
return false; }
}
/**
/** * 该方法用来判断文件是否存在,如果不存在则创建,该方法能够实现创建整个路径
* 该方法用来判断文件是否存在,如果不存在则创建,该方法能够实现创建整个路径 *
* * @param filePath
* @param filePath */
*/ public static boolean creatFiles(String filePath) {
public static boolean creatFiles(String filePath) { LOGGER.info("【文件API】创建文件,同时创建整个路径.<START>.[filePath]=" + filePath);
LOGGER.info("【文件API】创建文件,同时创建整个路径.<START>.[filePath]=" + filePath); if (StringUtil.isEmpty(filePath)) {
if (StringUtil.isEmpty(filePath)) { return false;
return false; }
} filePath = filePath.replace(File.separator, "/");
filePath = filePath.replace(File.separator, "/"); String dirPath = filePath.substring(0, filePath.lastIndexOf("/"));
String dirPath = filePath.substring(0, filePath.lastIndexOf("/")); File dirFile = new File(dirPath);
File dirFile = new File(dirPath); if (!dirFile.exists()) {
if (!dirFile.exists()) { try {
try { dirFile.mkdirs();
dirFile.mkdirs(); } catch (Exception e) {
} catch (Exception e) { LOGGER.error("【文件工具】创建文件夹失败,<ERROR>:" + e.getMessage(), e);
LOGGER.error("【文件工具】创建文件夹失败,<ERROR>:" + e.getMessage(), e); return false;
return false; }
} }
} File file = new File(filePath);
File file = new File(filePath); if (!file.exists()) {
if (!file.exists()) { try {
try { file.createNewFile();
file.createNewFile(); return true;
return true; } catch (Exception e) {
} catch (Exception e) { LOGGER.error("【文件工具】创建文件失败,<ERROR>:" + e.getMessage(), e);
LOGGER.error("【文件工具】创建文件失败,<ERROR>:" + e.getMessage(), e); }
} }
} LOGGER.info("【文件API】创建文件,同时创建整个路径.<END>");
LOGGER.info("【文件API】创建文件,同时创建整个路径.<END>"); return false;
return false; }
}
/**
/** * 该方法用来判断文件夹是否存在,如果不存在则创建,存在则什么都不做
* 该方法用来判断文件夹是否存在,如果不存在则创建,存在则什么都不做 *
* * @param filePath
* @param filePath */
*/ public static boolean creatDir(String filePath) {
public static boolean creatDir(String filePath) { if (StringUtil.isEmpty(filePath)) {
if (StringUtil.isEmpty(filePath)) { return false;
return false; }
} File file = new File(filePath);
File file = new File(filePath); if (!file.exists()) {
if (!file.exists()) { file.mkdir();
file.mkdir(); return true;
return true; }
} return false;
return false; }
}
/**
/** * 该方法用来判断文件夹是否存在,如果不存在则创建,存在则什么都不做 该方法能够实现创建整个路径
* 该方法用来判断文件夹是否存在,如果不存在则创建,存在则什么都不做 该方法能够实现创建整个路径 *
* * @param filePath
* @param filePath */
*/ public static boolean creatDirs(String filePath) {
public static boolean creatDirs(String filePath) { if (StringUtil.isEmpty(filePath)) {
if (StringUtil.isEmpty(filePath)) { return false;
return false; }
} File file = new File(filePath);
File file = new File(filePath); if (!file.exists()) {
if (!file.exists()) { file.mkdirs();
file.mkdirs(); return true;
return true; }
} return false;
return false; }
}
/**
/** * 获取文件类型
* 获取文件类型 *
* * @param filePath
* @param filePath */
*/ public static String getFileType(String filePath) {
public static String getFileType(String filePath) { if (StringUtil.isEmpty(filePath)) {
if (StringUtil.isEmpty(filePath)) { return null;
return null; }
} int index1 = filePath.lastIndexOf(".");
int index1 = filePath.lastIndexOf("."); if (index1 < 1) {
if (index1 < 1) { return null;
return null; }
} int index2 = filePath.lastIndexOf("?");
int index2 = filePath.lastIndexOf("?"); if (index2 > index1) {
if (index2 > index1) { filePath = filePath.substring(0, filePath.lastIndexOf("?"));
filePath = filePath.substring(0, filePath.lastIndexOf("?")); }
} filePath = filePath.replace("/", OSConstant.SEPARATOR);
filePath = filePath.replace("/", OSConstant.SEPARATOR); int index3 = filePath.lastIndexOf(OSConstant.SEPARATOR);
int index3 = filePath.lastIndexOf(OSConstant.SEPARATOR); if (index3 > index1) {
if (index3 > index1) { return null;
return null; }
} return filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length()).toLowerCase();
return filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length()).toLowerCase(); }
}
/**
/** * 获取文件名称
* 获取文件名称 *
* * @param filePath
* @param filePath */
*/ public static String getFileName(String filePath) {
public static String getFileName(String filePath) { if (StringUtil.isEmpty(filePath)) {
if (StringUtil.isEmpty(filePath)) { return null;
return null; }
} String fileName = null;
String fileName = null; filePath = filePath.replace("/", OSConstant.SEPARATOR);
filePath = filePath.replace("/", OSConstant.SEPARATOR); int index1 = filePath.lastIndexOf(".");
int index1 = filePath.lastIndexOf("."); if (index1 > -1) {
if (index1 > -1) { int index2 = filePath.lastIndexOf("?");
int index2 = filePath.lastIndexOf("?"); if (index2 > index1) {
if (index2 > index1) { filePath = filePath.substring(0, filePath.lastIndexOf("?"));
filePath = filePath.substring(0, filePath.lastIndexOf("?")); }
} int index3 = filePath.lastIndexOf(OSConstant.SEPARATOR);
int index3 = filePath.lastIndexOf(OSConstant.SEPARATOR); if (index3 > index1) {
if (index3 > index1) { fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1);
fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1); } else {
} else { fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1,
fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1, filePath.lastIndexOf("."));
filePath.lastIndexOf(".")); }
} } else {
} else { fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1);
fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1); }
} return formatName(fileName);
return formatName(fileName); }
}
/**
/** * 获取文件名称包括后缀
* 获取文件名称包括后缀 *
* * @param filePath
* @param filePath * @return
* @return */
*/ public static String getFileNameAll(String filePath) {
public static String getFileNameAll(String filePath) { if (StringUtil.isEmpty(filePath)) {
if (StringUtil.isEmpty(filePath)) { return null;
return null; }
} String fileName = getFileName(filePath);
String fileName = getFileName(filePath); if (StringUtil.isEmpty(fileName)) {
if (StringUtil.isEmpty(fileName)) { return null;
return null; }
} String fileType = getFileType(filePath);
String fileType = getFileType(filePath); return StringUtil.isEmpty(fileType) ? fileName : fileName + "." + fileType;
return StringUtil.isEmpty(fileType) ? fileName : fileName + "." + fileType; }
}
/**
/** * 格式化文件名称,过滤特殊字符(名称太长进行截断)
* 格式化文件名称,过滤特殊字符(名称太长进行截断) *
* * @param fileName
* @param fileName */
*/ public static String formatName(String fileName) {
public static String formatName(String fileName) { if (StringUtil.isEmpty(fileName)) {
if (StringUtil.isEmpty(fileName)) { return null;
return null; }
} try {
String regEx = "[*/\\\\:?\"<|>\\s+%#&=.()]"; String regEx = "[*/\\\\:?\"<|>\\s+%#&=.()]";
Pattern p = Pattern.compile(regEx); Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(fileName); Matcher m = p.matcher(fileName);
String result = m.replaceAll("").trim(); String result = m.replaceAll("").trim();
// 文件名称过长的话,限制40个字 // 文件名称过长的话,限制40个字
return result.length() > 40 ? result.substring(0, 40) : result; return result.length() > 40 ? result.substring(0, 40) : result;
} } catch (Exception e) {
LOGGER.error("【文件API】格式化文件名称.[formatName]:" + e.getMessage(), e);
/** return UUIDUitl.taskName();
* 获取文件所在的目录 }
* }
* @param filePath
* @return /**
*/ * 获取文件所在的目录
public static String getFileFolder(String filePath) { *
if (StringUtil.isEmpty(filePath)) { * @param filePath
return null; * @return
} */
return filePath.substring(0, filePath.lastIndexOf(OSConstant.SEPARATOR)); public static String getFileFolder(String filePath) {
} if (StringUtil.isEmpty(filePath)) {
return null;
}
return filePath.substring(0, filePath.lastIndexOf(OSConstant.SEPARATOR));
}
/** /**
* 获取http文件路径的域名 * 获取http文件路径的域名
...@@ -429,675 +434,662 @@ public class FileUtils { ...@@ -429,675 +434,662 @@ public class FileUtils {
return null; return null;
} }
/** /**
* FileUtils工具 File @throws * FileUtils工具 File @throws
*/ */
public static File copyURLToFile(String url, String dir) throws Exception { public static File copyURLToFile(String url, String dir) throws Exception {
try { try {
URL httpurl = new URL(url); URL httpurl = new URL(url);
File f = new File(dir); File f = new File(dir);
org.apache.commons.io.FileUtils.copyURLToFile(httpurl, f); org.apache.commons.io.FileUtils.copyURLToFile(httpurl, f);
return f; return f;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
/** /**
* 根据路径删除指定的目录或文件,无论存在与否 * 根据路径删除指定的目录或文件,无论存在与否
* *
* @param sPath * @param sPath 要删除的目录或文件
* 要删除的目录或文件 * @return 删除成功返回 true,否则返回 false。
* @return 删除成功返回 true,否则返回 false。 */
*/ public static boolean deleteFolder(String sPath) {
public static boolean deleteFolder(String sPath) { if (StringUtil.isEmpty(sPath)) {
if (StringUtil.isEmpty(sPath)) { return false;
return false; }
} boolean flag = false;
boolean flag = false; File file = new File(sPath);
File file = new File(sPath); // 判断目录或文件是否存在
// 判断目录或文件是否存在 if (!file.exists()) { // 不存在返回 false
if (!file.exists()) { // 不存在返回 false return flag;
return flag; } else {
} else { // 判断是否为文件
// 判断是否为文件 if (file.isFile()) { // 为文件时调用删除文件方法
if (file.isFile()) { // 为文件时调用删除文件方法 return deleteFile(sPath);
return deleteFile(sPath); } else { // 为目录时调用删除目录方法
} else { // 为目录时调用删除目录方法 return deleteDirectory(sPath);
return deleteDirectory(sPath); }
} }
} }
}
/**
/** * 删除单个文件
* 删除单个文件 *
* * @param sPath 被删除文件的文件名
* @param sPath * @return 单个文件删除成功返回true,否则返回false
* 被删除文件的文件名 */
* @return 单个文件删除成功返回true,否则返回false public static boolean deleteFile(String sPath) {
*/ if (StringUtil.isEmpty(sPath)) {
public static boolean deleteFile(String sPath) { return false;
if (StringUtil.isEmpty(sPath)) { }
return false; boolean flag = false;
} File file = new File(sPath);
boolean flag = false; // 路径为文件且不为空则进行删除
File file = new File(sPath); if (file.isFile() && file.exists()) {
// 路径为文件且不为空则进行删除 file.delete();
if (file.isFile() && file.exists()) { flag = true;
file.delete(); }
flag = true; return flag;
} }
return flag;
} /**
* 删除目录(文件夹)以及目录下的文件
/** *
* 删除目录(文件夹)以及目录下的文件 * @param sPath 被删除目录的文件路径
* * @return 目录删除成功返回true,否则返回false
* @param sPath */
* 被删除目录的文件路径 public static boolean deleteDirectory(String sPath) {
* @return 目录删除成功返回true,否则返回false if (StringUtil.isEmpty(sPath)) {
*/ return false;
public static boolean deleteDirectory(String sPath) { }
if (StringUtil.isEmpty(sPath)) { // 如果sPath不以文件分隔符结尾,自动添加文件分隔符
return false; if (!sPath.endsWith(File.separator)) {
} sPath = sPath + File.separator;
// 如果sPath不以文件分隔符结尾,自动添加文件分隔符 }
if (!sPath.endsWith(File.separator)) { File dirFile = new File(sPath);
sPath = sPath + File.separator; // 如果dir对应的文件不存在,或者不是一个目录,则退出
} if (!dirFile.exists() || !dirFile.isDirectory()) {
File dirFile = new File(sPath); return false;
// 如果dir对应的文件不存在,或者不是一个目录,则退出 }
if (!dirFile.exists() || !dirFile.isDirectory()) { boolean flag = true;
return false; // 删除文件夹下的所有文件(包括子目录)
} File[] files = dirFile.listFiles();
boolean flag = true; for (int i = 0; i < files.length; i++) {
// 删除文件夹下的所有文件(包括子目录) // 删除子文件
File[] files = dirFile.listFiles(); if (files[i].isFile()) {
for (int i = 0; i < files.length; i++) { flag = deleteFile(files[i].getAbsolutePath());
// 删除子文件 if (!flag)
if (files[i].isFile()) { break;
flag = deleteFile(files[i].getAbsolutePath()); } // 删除子目录
if (!flag) else {
break; flag = deleteDirectory(files[i].getAbsolutePath());
} // 删除子目录 if (!flag)
else { break;
flag = deleteDirectory(files[i].getAbsolutePath()); }
if (!flag) }
break; if (!flag)
} return false;
} // 删除当前目录
if (!flag) if (dirFile.delete()) {
return false; return true;
// 删除当前目录 } else {
if (dirFile.delete()) { return false;
return true; }
} else { }
return false;
} /**
} * 检查文件是否存在
*
/** * @param filePath
* 检查文件是否存在 * @return
* */
* @param path public static boolean checkFile(String filePath) {
* @return if (StringUtil.isEmpty(filePath)) {
*/ return false;
public static boolean checkFile(String filePath) { }
if (StringUtil.isEmpty(filePath)) { File file = new File(filePath);
return false; if (!file.isFile()) {
} return false;
File file = new File(filePath); }
if (!file.isFile()) { return true;
return false; }
}
return true; /**
} * | FileUtils工具
*/
/** public static void downloadFileFromUrl(String url, String localFilePath) throws FileException {
* | FileUtils工具 LOGGER.info("【文件API】下载文件[本地文件].<START>.[url]=" + url + ",[localFilePath]=" + localFilePath);
*/ creatFiles(localFilePath);
public static void downloadFileFromUrl(String url, String localFilePath) throws FileException { try {
LOGGER.info("【文件API】下载文件[本地文件].<START>.[url]=" + url + ",[localFilePath]=" + localFilePath); if (StringTools.contains(url, AliyunConstant.OSS_CDN_URLS)) {
creatFiles(localFilePath); OssUtils.downloadFile(url, localFilePath);
try { // } else if (url.contains("/group")) {
if (StringTools.contains(url, AliyunConstant.OSS_CDN_URLS)) { // Map<String, String> paramMap = FdfsUtils.splitFilePath(url);
OssUtils.downloadFile(url, localFilePath); // FdfsUtils.download(paramMap.get(FdfsEnum.GROUP_NAME.value),
// } else if (url.contains("/group")) { // paramMap.get(FdfsEnum.FILE_ID.value), localFilePath);
// Map<String, String> paramMap = FdfsUtils.splitFilePath(url); } else {
// FdfsUtils.download(paramMap.get(FdfsEnum.GROUP_NAME.value), File f = new File(localFilePath);
// paramMap.get(FdfsEnum.FILE_ID.value), localFilePath); URL httpurl = new URL(url);
} else { org.apache.commons.io.FileUtils.copyURLToFile(httpurl, f);
File f = new File(localFilePath); }
URL httpurl = new URL(url); } catch (Exception e) {
org.apache.commons.io.FileUtils.copyURLToFile(httpurl, f); LOGGER.error("【文件API】下载文件.[copyURLToFile]:" + e.getMessage(), e);
} throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
} catch (Exception e) { }
LOGGER.error("【文件API】下载文件.[copyURLToFile]:" + e.getMessage(), e); }
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
} /**
} * IOUtils工具
*/
/** public static byte[] downloadByteFromUrl(String url) throws FileException {
* IOUtils工具 LOGGER.info("【文件API】下载文件[byte].<START>.[url]=" + url);
*/ if (StringUtil.isEmpty(url)) {
public static byte[] downloadByteFromUrl(String url) throws FileException { return null;
LOGGER.info("【文件API】下载文件[byte].<START>.[url]=" + url); }
if (StringUtil.isEmpty(url)) { byte[] data = null;
return null; try {
} if (StringTools.contains(url, AliyunConstant.OSS_CDN_URLS)) {
byte[] data = null; data = OssUtils.downloadFile2Byte(url);
try { // } else if (url.contains("/group")) {
if (StringTools.contains(url, AliyunConstant.OSS_CDN_URLS)) { // Map<String, String> paramMap = FdfsUtils.splitFilePath(url);
data = OssUtils.downloadFile2Byte(url); // data =
// } else if (url.contains("/group")) { // FdfsUtils.download(paramMap.get(FdfsEnum.GROUP_NAME.value),
// Map<String, String> paramMap = FdfsUtils.splitFilePath(url); // paramMap.get(FdfsEnum.FILE_ID.value));
// data = } else {
// FdfsUtils.download(paramMap.get(FdfsEnum.GROUP_NAME.value), URL httpurl = new URL(url);
// paramMap.get(FdfsEnum.FILE_ID.value)); data = IOUtils.toByteArray(httpurl);
} else { }
URL httpurl = new URL(url); } catch (Exception e) {
data = IOUtils.toByteArray(httpurl); LOGGER.error("【文件API】下载文件.[toByteArray]:" + e.getMessage(), e);
} throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
} catch (Exception e) { }
LOGGER.error("【文件API】下载文件.[toByteArray]:" + e.getMessage(), e); return data;
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败"); }
}
return data; /**
} * InputStream
*/
/** @Deprecated
* InputStream public static InputStream downloadStreamFromUrl(String url) throws FileException {
*/ try {
@Deprecated URL httpurl = new URL(url);
public static InputStream downloadStreamFromUrl(String url) throws FileException { return httpurl.openStream();
try { } catch (Exception e) {
URL httpurl = new URL(url); LOGGER.error("【文件API】下载文件.[openStream]:" + e.getMessage(), e);
return httpurl.openStream(); throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
} catch (Exception e) { }
LOGGER.error("【文件API】下载文件.[openStream]:" + e.getMessage(), e); }
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
} /**
} * 普通情况下保存字节数据到本地文件
*/
/** public synchronized static boolean saveBytesTofile(File file, byte[] data) throws BizException {
* 普通情况下保存字节数据到本地文件 FileOutputStream fos = null;
*/ // 建立输出字节流
public synchronized static boolean saveBytesTofile(File file, byte[] data) throws BizException { try {
FileOutputStream fos = null; fos = new FileOutputStream(file);
// 建立输出字节流 fos.write(data); // 用FileOutputStream 的write方法写入字节数组
try { return true;
fos = new FileOutputStream(file); } catch (Exception e) {
fos.write(data); // 用FileOutputStream 的write方法写入字节数组 e.printStackTrace();
return true; return false;
} catch (Exception e) { } finally {
e.printStackTrace(); try {
return false; fos.close();
} finally { } catch (IOException e) {
try { e.printStackTrace();
fos.close(); }
} catch (IOException e) { }
e.printStackTrace(); }
}
} /**
} * 复制一个文件到另一个目录下
*
/** * @throws BizException
* 复制一个文件到另一个目录下 */
* public static void copyFileToFolder(File inputFile, File outputFile) throws BizException {
* @throws BizException FileInputStream fis = null;
*/ FileOutputStream fos = null;
public static void copyFileToFolder(File inputFile, File outputFile) throws BizException {
FileInputStream fis = null; try {
FileOutputStream fos = null; fis = new FileInputStream(inputFile);
fos = new FileOutputStream(outputFile);
try { int len = 0;
fis = new FileInputStream(inputFile); byte[] buf = new byte[1024];
fos = new FileOutputStream(outputFile); while ((len = fis.read(buf)) != -1) {
int len = 0; fos.write(buf, 0, len);
byte[] buf = new byte[1024]; }
while ((len = fis.read(buf)) != -1) { fis.close();
fos.write(buf, 0, len); fos.close();
} } catch (IOException ioe) {
fis.close(); ioe.printStackTrace();
fos.close(); }
} catch (IOException ioe) { }
ioe.printStackTrace();
} /**
} * 合并两个文件
*
/** * @param outFile 目标文件
* 合并两个文件 * @param leafFile 源文件
* */
* @param outFile public static void mergeFiles(File outFile, File leafFile) {
* 目标文件 FileOutputStream fos = null;
* @param files FileInputStream fis = null;
* 源文件 if (!outFile.exists()) {
*/ try {
public static void mergeFiles(File outFile, File leafFile) { outFile.createNewFile();
FileOutputStream fos = null; } catch (Exception e) {
FileInputStream fis = null; throw new FileException(FileException.FILE_NOT_EXIST, "创建临时存储文件失败");
if (!outFile.exists()) { }
try { }
outFile.createNewFile(); try {
} catch (Exception e) { // 合并其实就是文件的续写,写成true
throw new FileException(FileException.FILE_NOT_EXIST, "创建临时存储文件失败"); fos = new FileOutputStream(outFile, true);
} fis = new FileInputStream(leafFile);
} int len = 0;
try { for (byte[] buf = new byte[1024 * 1024]; (len = fis.read(buf)) != -1; ) {
// 合并其实就是文件的续写,写成true fos.write(buf, 0, len);
fos = new FileOutputStream(outFile, true); }
fis = new FileInputStream(leafFile); } catch (IOException ioe) {
int len = 0; ioe.printStackTrace();
for (byte[] buf = new byte[1024 * 1024]; (len = fis.read(buf)) != -1;) { } finally {
fos.write(buf, 0, len); try {
} if (fis != null)
} catch (IOException ioe) { fis.close();
ioe.printStackTrace(); if (fos != null)
} finally { fos.close();
try { } catch (Exception e) {
if (fis != null) }
fis.close(); }
if (fos != null) }
fos.close();
} catch (Exception e) { /**
} * 合并多个文件
} *
} * @param outFile 输出文件,
* @param leafFiles 文件碎片集
/** */
* 合并多个文件 public static void mergeFileList(File outFile, List<File> leafFiles) {
* FileOutputStream fos = null;
* @param outFile FileInputStream fis = null;
* 输出文件, if (!outFile.exists()) {
* @param leafFile try {
* 文件碎片集 outFile.createNewFile();
*/ } catch (Exception e) {
public static void mergeFileList(File outFile, List<File> leafFiles) { throw new FileException(FileException.FILE_NOT_EXIST, "创建临时存储文件失败");
FileOutputStream fos = null; }
FileInputStream fis = null; }
if (!outFile.exists()) { try {
try { // 合并其实就是文件的续写,写成true
outFile.createNewFile(); fos = new FileOutputStream(outFile, true);
} catch (Exception e) { byte[] buf = new byte[1024 * 1024];
throw new FileException(FileException.FILE_NOT_EXIST, "创建临时存储文件失败"); for (File leafFile : leafFiles) {
} fis = new FileInputStream(leafFile);
} int len = 0;
try { while ((len = fis.read(buf)) != -1) {
// 合并其实就是文件的续写,写成true fos.write(buf, 0, len);
fos = new FileOutputStream(outFile, true); }
byte[] buf = new byte[1024 * 1024]; }
for (File leafFile : leafFiles) { } catch (IOException ioe) {
fis = new FileInputStream(leafFile); ioe.printStackTrace();
int len = 0; } finally {
while ((len = fis.read(buf)) != -1) { try {
fos.write(buf, 0, len); if (fis != null)
} fis.close();
} if (fos != null)
} catch (IOException ioe) { fos.close();
ioe.printStackTrace(); } catch (Exception e) {
} finally { }
try { }
if (fis != null) }
fis.close();
if (fos != null) /**
fos.close(); * 音频文件转换
} catch (Exception e) { *
} * @param data 音频byte数组
} * @param sourExt 原始后缀
} * @param ext 新后缀
* @return
/** * @author PENG
* 音频文件转换 */
* public static String audioFormatConvert(byte[] data, String sourExt, String ext) {
* @author PENG File tmpdir = new File("tempdir/local");
* @param data if (!tmpdir.exists()) {
* 音频byte数组 try {
* @param sourExt tmpdir.mkdirs();
* 原始后缀 } catch (SecurityException ex) {
* @param ext System.out.println("无法创建临时文件夹");
* 新后缀 ex.printStackTrace();
* @return }
*/ }
public static String audioFormatConvert(byte[] data, String sourExt, String ext) {
File tmpdir = new File("tempdir/local"); String name = UUID.randomUUID().toString();
if (!tmpdir.exists()) { File source = new File(tmpdir, name + "." + sourExt);
try { boolean creat = saveBytesTofile(source, data);
tmpdir.mkdirs(); if (creat) {
} catch (SecurityException ex) { File target = new File(tmpdir, name + "." + ext);
System.out.println("无法创建临时文件夹"); AudioAttributes audio = new AudioAttributes();
ex.printStackTrace(); Encoder encoder = new Encoder();
} audio.setCodec("libmp3lame");
}
EncodingAttributes attrs = new EncodingAttributes();
String name = UUID.randomUUID().toString(); attrs.setFormat(ext.toLowerCase());
File source = new File(tmpdir, name + "." + sourExt); attrs.setAudioAttributes(audio);
boolean creat = saveBytesTofile(source, data);
if (creat) { try {
File target = new File(tmpdir, name + "." + ext); encoder.encode(source, target, attrs);
AudioAttributes audio = new AudioAttributes(); return target.getPath();
Encoder encoder = new Encoder(); } catch (IllegalArgumentException e) {
audio.setCodec("libmp3lame"); e.printStackTrace();
return null;
EncodingAttributes attrs = new EncodingAttributes(); } catch (InputFormatException e) {
attrs.setFormat(ext.toLowerCase()); e.printStackTrace();
attrs.setAudioAttributes(audio); return null;
} catch (EncoderException e) {
try { e.printStackTrace();
encoder.encode(source, target, attrs); return target.getPath();
return target.getPath(); }
} catch (IllegalArgumentException e) { } else {
e.printStackTrace(); return null;
return null; }
} catch (InputFormatException e) { }
e.printStackTrace();
return null; /**
} catch (EncoderException e) { * 获取文本的内容
e.printStackTrace(); *
return target.getPath(); * @param url
} * @return
} else { */
return null; public static String getTextString(String url) {
} LOGGER.info("【文件API】获取文本的内容.<START>.[url]=" + url);
} if (StringUtil.isEmpty(url)) {
return null;
/** }
* 获取文本的内容 StringBuilder lrcString = new StringBuilder();
* InputStream is = null;
* @param url InputStreamReader isr = null;
* @return try {
*/ byte[] bt = downloadByteFromUrl(url);
public static String getTextString(String url) { is = new ByteArrayInputStream(bt);
LOGGER.info("【文件API】获取文本的内容.<START>.[url]=" + url); boolean isUTF8Bom = CpdetectorEncoding.isUTF8Bom(is);
if (StringUtil.isEmpty(url)) { if (isUTF8Bom) {
return null; isr = new InputStreamReader(is, "UTF-8");
} } else {
StringBuilder lrcString = new StringBuilder(); Object charSet = CpdetectorEncoding.getEncoding(bt, false);
InputStream is = null; if (charSet.toString().equals("UTF-8")) {
InputStreamReader isr = null; isr = new InputStreamReader(is, "UTF-8");
try { } else {
byte[] bt = downloadByteFromUrl(url); isr = new InputStreamReader(new ByteArrayInputStream(bt), "GBK");
is = new ByteArrayInputStream(bt); }
boolean isUTF8Bom = CpdetectorEncoding.isUTF8Bom(is); }
if (isUTF8Bom) { BufferedReader br = new BufferedReader(isr);// 构造一个BufferedReader类来读取文件
isr = new InputStreamReader(is, "UTF-8"); String s;
} else { while ((s = br.readLine()) != null) {// 使用readLine方法,一次读一行
Object charSet = CpdetectorEncoding.getEncoding(bt, false); lrcString.append(System.lineSeparator() + s);
if (charSet.toString().equals("UTF-8")) { }
isr = new InputStreamReader(is, "UTF-8"); } catch (Exception e) {
} else { LOGGER.error("【文件工具】读取文件内容.<ERROR>:" + e.getMessage(), e);
isr = new InputStreamReader(new ByteArrayInputStream(bt), "GBK"); } finally {
} try {
} if (isr != null)
BufferedReader br = new BufferedReader(isr);// 构造一个BufferedReader类来读取文件 isr.close();
String s; if (is != null)
while ((s = br.readLine()) != null) {// 使用readLine方法,一次读一行 is.close();
lrcString.append(System.lineSeparator() + s); } catch (Exception e2) {
} }
} catch (Exception e) { }
LOGGER.error("【文件工具】读取文件内容.<ERROR>:" + e.getMessage(), e); LOGGER.info("【文件API】获取文本的内容.<END>");
} finally { return lrcString.toString();
try { }
if (isr != null)
isr.close(); /**
if (is != null) * java 8 读取文本内容
is.close(); *
} catch (Exception e2) { * @param url
} * @return
} */
LOGGER.info("【文件API】获取文本的内容.<END>"); public static String getTextString8(String url) {
return lrcString.toString(); LOGGER.info("【文件API】获取文本的内容8.<START>.[url]=" + url);
} StringBuilder result = new StringBuilder();
String fileType = getFileType(url);
/** String localFilePath = url;
* java 8 读取文本内容 if (url.startsWith("http")) {
* localFilePath = FilePathConst.TEXT_PATH + UUIDUitl.taskName() + "." + fileType;
* @param url downloadFileFromUrl(url, localFilePath);
* @return }
*/ try {
public static String getTextString8(String url) { Stream<String> lines = Files.lines(Paths.get(localFilePath), StandardCharsets.UTF_8);
LOGGER.info("【文件API】获取文本的内容8.<START>.[url]=" + url); lines.forEach(line -> {
StringBuilder result = new StringBuilder(); result.append(line + System.lineSeparator());
String fileType = getFileType(url); });
String localFilePath = FilePathConst.TEXT_PATH + UUIDUitl.taskName() + "." + fileType; } catch (Exception e) {
downloadFileFromUrl(url, localFilePath); LOGGER.error("【文件工具】读取文件内容8.<ERROR>:" + e.getMessage(), e);
try { } finally {
List<String> lines = Files.readAllLines(Paths.get(localFilePath), StandardCharsets.UTF_8); deleteFile(localFilePath);
for (String line : lines) { }
result.append(line + System.lineSeparator()); LOGGER.info("【文件API】获取文本的内容8.<END>");
} return result.toString();
} catch (Exception e) { }
LOGGER.error("【文件工具】读取文件内容8.<ERROR>:" + e.getMessage(), e);
} /**
deleteFile(localFilePath); * 文件剪切,网络路径、按文件大小的百分比
LOGGER.info("【文件API】获取文本的内容8.<END>"); *
return result.toString(); * @param url
} * @param percent 1~100的整数
* @return 返回剪切后上传后的文件路径
/** * @throws BizException
* 文件剪切,网络路径、按文件大小的百分比 */
* public static String clipByPercent(String url, int percent) throws BizException {
* @param inputFile LOGGER.info("【文件API】文件剪切,按百分比.<START>.[url]=" + url);
* @param cutPercent if (StringUtil.isEmpty(url)) {
* 1~100的整数 return null;
* @return 返回剪切后上传后的文件路径 }
* @throws BizException String fileType = FileUtils.getFileType(url);
*/ if (!FileUtils.VIDEO.equals(FileUtils.getGatherName(fileType))) {
public static String clipByPercent(String url, int percent) throws BizException { return null;
LOGGER.info("【文件API】文件剪切,按百分比.<START>.[url]=" + url); }
if (StringUtil.isEmpty(url)) { // 下载文件
return null; String downloadPath = FilePathConst.DOWNLOAD_PATH + UUIDUitl.generateString(32) + "." + fileType;
} FileUtils.downloadFileFromUrl(url, downloadPath);
String fileType = FileUtils.getFileType(url); // 剪切文件
if (!FileUtils.VIDEO.equals(FileUtils.getGatherName(fileType))) { String cutPath = clipByPercent(new File(downloadPath), percent);
return null; // 重新上传文件
} UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile(cutPath, null);
// 下载文件 // 删除本地文件
String downloadPath = FilePathConst.DOWNLOAD_PATH + UUIDUitl.generateString(32) + "." + fileType; FileUtils.deleteFile(downloadPath);
FileUtils.downloadFileFromUrl(url, downloadPath); FileUtils.deleteFile(cutPath);
// 剪切文件 LOGGER.info("【文件API】文件剪切,按百分比.<END>.[uploadResultInfo]=" + uploadResultInfo);
String cutPath = clipByPercent(new File(downloadPath), percent); return uploadResultInfo == null ? null : uploadResultInfo.getUrl();
// 重新上传文件 }
UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile(cutPath, null);
// 删除本地文件 /**
FileUtils.deleteFile(downloadPath); * 文件剪切,本地路径、按百分比
FileUtils.deleteFile(cutPath); *
LOGGER.info("【文件API】文件剪切,按百分比.<END>.[uploadResultInfo]=" + uploadResultInfo); * @param inputFile
return uploadResultInfo == null ? null : uploadResultInfo.getUrl(); * @param cutPercent 1~100的整数
} * @return 返回本地路径地址
* @throws BizException
/** */
* 文件剪切,本地路径、按百分比 public static String clipByPercent(File inputFile, int cutPercent) throws BizException {
* LOGGER.info("【文件API】文件剪切.<START>.[cutPercent]=" + cutPercent);
* @param inputFile if (inputFile == null || inputFile.length() <= 0) {
* @param cutPercent throw new FileException(FileException.FILE_NOT_EXIST, "不是有效的文件");
* 1~100的整数 }
* @return 返回本地路径地址 if (cutPercent > 100 || cutPercent < 1) {
* @throws BizException throw new FileException(FileException.FILE_READ_FAILURE, "百分比必须是1~100之间的整数");
*/ }
public static String clipByPercent(File inputFile, int cutPercent) throws BizException { return clipByLength(inputFile, Math.round(inputFile.length() * cutPercent / 100.0d));
LOGGER.info("【文件API】文件剪切.<START>.[cutPercent]=" + cutPercent); }
if (inputFile == null || inputFile.length() <= 0) {
throw new FileException(FileException.FILE_NOT_EXIST, "不是有效的文件"); /**
} * 文件剪切
if (cutPercent > 100 || cutPercent < 1) { *
throw new FileException(FileException.FILE_READ_FAILURE, "百分比必须是1~100之间的整数"); * @param inputFile 待剪切的文件
} * @param cutLength 剪切长度(Byte)
return clipByLength(inputFile, Math.round(inputFile.length() * cutPercent / 100.0d)); */
} public static String clipByLength(File inputFile, long cutLength) throws BizException {
LOGGER.info("【文件API】文件剪切.<START>.[cutLength]=" + cutLength);
/** if (inputFile == null || inputFile.length() <= 0) {
* 文件剪切 throw new FileException(FileException.FILE_NOT_EXIST, "不是有效的文件");
* }
* @param inputFile if (cutLength < 1024) {
* 待剪切的文件 throw new FileException(FileException.FILE_READ_FAILURE, "剪切的文件必须大于1KB");
* @param outputFile }
* 剪切后的文件 // 输出文件路径
* @param cutLength String outFilePath = FilePathConst.CUT_PATH + UUIDUitl.generateString(12) + "_" + inputFile.getName();
* 剪切长度(Byte) creatFiles(outFilePath);
*/ // 剪切长度
public static String clipByLength(File inputFile, long cutLength) throws BizException { cutLength = cutLength > inputFile.length() ? inputFile.length() : cutLength;
LOGGER.info("【文件API】文件剪切.<START>.[cutLength]=" + cutLength); BufferedInputStream bis = null;
if (inputFile == null || inputFile.length() <= 0) { BufferedOutputStream bos = null;
throw new FileException(FileException.FILE_NOT_EXIST, "不是有效的文件"); try {
} // 两个输入流
if (cutLength < 1024) { bis = new BufferedInputStream(new FileInputStream(inputFile));
throw new FileException(FileException.FILE_READ_FAILURE, "剪切的文件必须大于1KB"); // 缓冲字节输出流
} bos = new BufferedOutputStream(new FileOutputStream(outFilePath));
// 输出文件路径 // 读取多少次
String outFilePath = FilePathConst.CUT_PATH + UUIDUitl.generateString(12) + "_" + inputFile.getName(); long index = cutLength % 1024 > 0 ? cutLength / 1024 + 1 : cutLength / 1024;
creatFiles(outFilePath); int mod = (int) cutLength % 1024;
// 剪切长度 byte[] bt = new byte[1024];
cutLength = cutLength > inputFile.length() ? inputFile.length() : cutLength; int len = 0;
BufferedInputStream bis = null; for (int i = 0; i < index; i++) {
BufferedOutputStream bos = null; if (i + 1 == index && mod != 0) {
try { bt = new byte[mod];
// 两个输入流 len = bis.read(bt);
bis = new BufferedInputStream(new FileInputStream(inputFile)); } else {
// 缓冲字节输出流 len = bis.read(bt);
bos = new BufferedOutputStream(new FileOutputStream(outFilePath)); }
// 读取多少次 if (len != -1) {
long index = cutLength % 1024 > 0 ? cutLength / 1024 + 1 : cutLength / 1024; bos.write(bt, 0, len);
int mod = (int) cutLength % 1024; }
byte[] bt = new byte[1024]; }
int len = 0; bos.flush();
for (int i = 0; i < index; i++) { } catch (IOException e) {
if (i + 1 == index && mod != 0) { LOGGER.error("【文件工具】剪切文件内容:" + e.getMessage(), e);
bt = new byte[mod]; throw new FileException(FileException.FILE_READ_FAILURE, "文件剪切失败");
len = bis.read(bt); } finally {
} else { try {
len = bis.read(bt); if (bis != null)
} bis.close();
if (len != -1) { if (bos != null)
bos.write(bt, 0, len); bos.close();
} } catch (IOException e) {
} LOGGER.error("【文件工具】文件流关闭失败:" + e.getMessage(), e);
bos.flush(); }
} catch (IOException e) { }
LOGGER.error("【文件工具】剪切文件内容:" + e.getMessage(), e); LOGGER.info("【文件API】文件剪切.<END>");
throw new FileException(FileException.FILE_READ_FAILURE, "文件剪切失败"); return outFilePath;
} finally { }
try {
if (bis != null) /**
bis.close(); * 将文件转成base64 字符串
if (bos != null) *
bos.close(); * @param data
} catch (IOException e) { * @return *
LOGGER.error("【文件工具】文件流关闭失败:" + e.getMessage(), e); * @throws Exception
} */
} public static String encodeBase64File(byte[] data) throws BizException {
LOGGER.info("【文件API】文件剪切.<END>"); try {
return outFilePath; return new String(Base64.encodeBase64(data));
} } catch (Exception e) {
LOGGER.error("【文件工具】将base64字符解码保存文件失败:" + e.getMessage(), e);
/** return null;
* 将文件转成base64 字符串 }
* }
* @param path文件路径
* @return * /**
* @throws Exception * 将base64字符解码保存文件
*/ *
public static String encodeBase64File(byte[] data) throws BizException { * @param base64Code
try { * @param targetPath
return new String(Base64.encodeBase64(data)); * @throws Exception
} catch (Exception e) { */
LOGGER.error("【文件工具】将base64字符解码保存文件失败:" + e.getMessage(), e); public static boolean decoderBase64File(String base64Code, String targetPath) throws BizException {
return null; if (base64Code == null)
} return false;
} OutputStream out = null;
try {
/** // Base64解码
* 将base64字符解码保存文件 byte[] b = Base64.decodeBase64(targetPath);
* for (int i = 0; i < b.length; ++i) {
* @param base64Code if (b[i] < 0) {// 调整异常数据
* @param targetPath b[i] += 256;
* @throws Exception }
*/ }
public static boolean decoderBase64File(String base64Code, String targetPath) throws BizException { // 生成jpeg图片
if (base64Code == null) out = new FileOutputStream(targetPath);
return false; out.write(b);
OutputStream out = null; out.flush();
try { } catch (Exception e) {
// Base64解码 LOGGER.error("【文件工具】将base64字符解码保存文件失败:" + e.getMessage(), e);
byte[] b = Base64.decodeBase64(targetPath); return false;
for (int i = 0; i < b.length; ++i) { } finally {
if (b[i] < 0) {// 调整异常数据 try {
b[i] += 256; if (out != null)
} out.close();
} } catch (Exception e) {
// 生成jpeg图片 }
out = new FileOutputStream(targetPath); }
out.write(b); return true;
out.flush(); }
} catch (Exception e) {
LOGGER.error("【文件工具】将base64字符解码保存文件失败:" + e.getMessage(), e); /**
return false; * 本地文件到byte数组
} finally { *
try { * @param path
if (out != null) * @return
out.close(); */
} catch (Exception e) { public static byte[] file2byte(String path) {
} byte[] data = null;
} FileInputStream fis = null;
return true; ByteArrayOutputStream os = null;
} try {
fis = new FileInputStream(new File(path));
/** os = new ByteArrayOutputStream();
* 本地文件到byte数组 byte[] buf = new byte[1024];
* int numBytesRead = 0;
* @param path while ((numBytesRead = fis.read(buf)) != -1) {
* @return os.write(buf, 0, numBytesRead);
*/ }
public static byte[] file2byte(String path) { data = os.toByteArray();
byte[] data = null; } catch (Exception e) {
FileInputStream fis = null; LOGGER.error("【文件工具】文件到byte数组:" + e.getMessage(), e);
ByteArrayOutputStream os = null; } finally {
try { try {
fis = new FileInputStream(new File(path)); if (fis != null)
os = new ByteArrayOutputStream(); fis.close();
byte[] buf = new byte[1024]; if (os != null)
int numBytesRead = 0; os.close();
while ((numBytesRead = fis.read(buf)) != -1) { } catch (IOException e) {
os.write(buf, 0, numBytesRead); LOGGER.error("【文件工具】文件流关闭失败:" + e.getMessage(), e);
} }
data = os.toByteArray(); }
} catch (Exception e) { return data;
LOGGER.error("【文件工具】文件到byte数组:" + e.getMessage(), e); }
} finally {
try { /**
if (fis != null) * 从输入流中获取数据
fis.close(); *
if (os != null) * @param inStream 输入流
os.close(); * @return
} catch (IOException e) { * @throws Exception
LOGGER.error("【文件工具】文件流关闭失败:" + e.getMessage(), e); */
} public static byte[] readInputStream(InputStream inStream) throws Exception {
} ByteArrayOutputStream outStream = new ByteArrayOutputStream();
return data; byte[] buffer = new byte[1024];
} int len = 0;
try {
/** while ((len = inStream.read(buffer)) != -1) {
* 从输入流中获取数据 outStream.write(buffer, 0, len);
* }
* @param inStream } catch (Exception e) {
* 输入流 LOGGER.error("【文件工具】文件流到byte数组:" + e.getMessage(), e);
* @return } finally {
* @throws Exception inStream.close();
*/ }
public static byte[] readInputStream(InputStream inStream) throws Exception { return outStream.toByteArray();
ByteArrayOutputStream outStream = new ByteArrayOutputStream(); }
byte[] buffer = new byte[1024];
int len = 0;
try {
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
} catch (Exception e) {
LOGGER.error("【文件工具】文件流到byte数组:" + e.getMessage(), e);
} finally {
inStream.close();
}
return outStream.toByteArray();
}
} }
...@@ -18,12 +18,16 @@ import org.slf4j.LoggerFactory; ...@@ -18,12 +18,16 @@ import org.slf4j.LoggerFactory;
import com.github.junrar.Archive; import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader; import com.github.junrar.rarfile.FileHeader;
import com.google.common.collect.Lists;
import com.pcloud.common.constant.OSConstant; import com.pcloud.common.constant.OSConstant;
import com.pcloud.common.dto.CompressDTO;
import com.pcloud.common.dto.CompressDTO.CompressFileDTO;
import com.pcloud.common.entity.UploadResultInfo; import com.pcloud.common.entity.UploadResultInfo;
import com.pcloud.common.exceptions.BizException; import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.exceptions.FileException; import com.pcloud.common.exceptions.FileException;
import com.pcloud.common.utils.FileUtils; import com.pcloud.common.utils.FileUtils;
import com.pcloud.common.utils.ListUtils; import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.LocalDateUtils;
import com.pcloud.common.utils.UUIDUitl; import com.pcloud.common.utils.UUIDUitl;
import com.pcloud.common.utils.aliyun.OssUtils; import com.pcloud.common.utils.aliyun.OssUtils;
import com.pcloud.common.utils.string.StringUtil; import com.pcloud.common.utils.string.StringUtil;
...@@ -35,357 +39,406 @@ import com.pcloud.common.utils.string.StringUtil; ...@@ -35,357 +39,406 @@ import com.pcloud.common.utils.string.StringUtil;
*/ */
public class CompressUtils { public class CompressUtils {
/** /**
* *
*/ */
private static final Logger LOGGER = LoggerFactory.getLogger(CompressUtils.class); private static final Logger LOGGER = LoggerFactory.getLogger(CompressUtils.class);
/** /**
* 压缩文件临时基础路径 * 压缩文件临时基础路径
*/ */
private static String FILE_LOCAL_PATH = OSConstant.USERDIR + "/download/"; private static String FILE_LOCAL_PATH = OSConstant.USERDIR + "/download/";
/** /**
* 压缩文件临时基础路径 * 压缩文件临时基础路径
*/ */
private static String ZIP_FILE_PATH = OSConstant.USERDIR + "/zip/"; private static String ZIP_FILE_PATH = OSConstant.USERDIR + "/zip/";
/** /**
* 压缩文件 * 分拆大小值
* */
* @param fileUrlList private static long CUT_SIZE = 1 * 1024 * 1024 * 1024;
* String[0]=文件名称, String[1]=文件地址
* @param zipName
* @return
* @throws BizException
*/
public static UploadResultInfo zip(List<String[]> fileUrlList, String zipName) throws BizException {
LOGGER.info("【压缩】压缩文件.<START>");
if (ListUtils.isEmpty(fileUrlList)) {
return null;
}
zipName = FileUtils.formatName(zipName);
String tempZipName = zipName + "_" + UUIDUitl.generateString(12);
// 检查临时文件夹是否存在,不存在就创建
String fileFolderPath = FILE_LOCAL_PATH + tempZipName;
FileUtils.isDir(fileFolderPath);
// 下载文件到文件夹中
int idx = 1;
for (String[] files : fileUrlList) {
String fileType = FileUtils.getFileType(files[1]);
String fileName = FileUtils.formatName(files[0]);
String downloadLocalPath = fileFolderPath + "/" + fileName + "_" + idx + "." + fileType;
FileUtils.downloadFileFromUrl(files[1], downloadLocalPath);
idx++;
}
// 检查压缩包临时文件夹是否存在,不存在就创建
FileUtils.isDir(ZIP_FILE_PATH);
String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip";
try {
CompressUtils.zip(fileFolderPath, zipFilePath);
} catch (Exception e) {
LOGGER.error("【压缩】压缩失败,<ERROR>:" + e.getMessage(), e);
throw new FileException(FileException.ZIP_ERROR, "压缩失败!");
}
// 上传文件到服务器中
UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, zipName);
// 删除产生的文件
FileUtils.deleteDirectory(fileFolderPath);
FileUtils.deleteFile(zipFilePath);
LOGGER.info("【压缩】压缩文件.<END>");
return uploadResultInfo;
}
/** /**
* 压缩文件(带目录) * 分批次打包,压缩文件集超过指定大小后,分多个包压缩,目前限定1个压缩包1G。
* *
* @param catalogFiles * @param compressDTO
* key : 目录名 String[0]=文件名称, String[1]=文件地址 * @return
* @param zipName * @throws BizException
* @return */
* @throws BizException public static List<UploadResultInfo> zips(CompressDTO compressDTO) throws BizException {
*/ LOGGER.info("【压缩】分批次打包文件.<START>.[compressDTO]=" + compressDTO);
public static UploadResultInfo zipByCatalog(Map<String, List<String[]>> catalogFiles, String zipName) if (compressDTO == null) {
throws BizException { return null;
LOGGER.info("【压缩】压缩文件.<START>"); }
if (MapUtils.isEmpty(catalogFiles)) { List<CompressFileDTO> compressFileDTOs = compressDTO.getCompressFileDTOs();
return null; if (ListUtils.isEmpty(compressFileDTOs)) {
} return null;
zipName = FileUtils.formatName(zipName); }
String tempZipName = zipName + "_" + UUIDUitl.generateString(12); List<UploadResultInfo> uploadResultInfos = Lists.newArrayList();
String parentPath = FILE_LOCAL_PATH + tempZipName; List<String[]> fileUrlList = Lists.newArrayList();
FileUtils.isDir(parentPath); long totalFileSize = 0;
for (String catalog : catalogFiles.keySet()) { int size = compressFileDTOs.size();
String downloadPath; int index = 1;
// 检查临时文件夹是否存在,不存在就创建 for (int i = 0; i < size; i++) {
if (!StringUtil.isEmpty(catalog)) { CompressFileDTO compressFileDTO = compressFileDTOs.get(i);
String catalogFolderPath = parentPath + "/" + catalog; totalFileSize += compressFileDTO.getFileSize();
FileUtils.isDir(catalogFolderPath); fileUrlList.add(new String[]{compressFileDTO.getFileName(), compressFileDTO.getFileUrl()});
downloadPath = catalogFolderPath; if (totalFileSize > CUT_SIZE) {
} else { String zipName = compressDTO.getCompressName() + "_" + index;
downloadPath = parentPath; UploadResultInfo uploadResultInfo = zip(fileUrlList, zipName);
} uploadResultInfo.setUrl(OssUtils.urlAddKeyLong2Short(uploadResultInfo.getUrl()));
List<String[]> fileUrlList = catalogFiles.get(catalog); uploadResultInfo.setFileItemCount(fileUrlList.size());
// 下载文件到文件夹中 uploadResultInfos.add(uploadResultInfo);
int idx = 1; // 零时变量复位
for (String[] files : fileUrlList) { totalFileSize = 0;
String fileType = FileUtils.getFileType(files[1]); fileUrlList = Lists.newArrayList();
String fileName = FileUtils.formatName(files[0]); index++;
String downloadLocalPath = downloadPath + "/" + fileName + "_" + idx + "." + fileType; }
FileUtils.downloadFileFromUrl(files[1], downloadLocalPath); }
idx++; // 打包剩余总大小不足1G的文件
} if (fileUrlList.size() > 0) {
} UploadResultInfo uploadResultInfo = zip(fileUrlList, compressDTO.getCompressName() + "_" + index);
// 检查压缩包临时文件夹是否存在,不存在就创建 uploadResultInfo.setUrl(OssUtils.urlAddKeyLong2Short(uploadResultInfo.getUrl()));
FileUtils.isDir(ZIP_FILE_PATH); uploadResultInfo.setFileItemCount(fileUrlList.size());
String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip"; uploadResultInfos.add(uploadResultInfo);
try { }
CompressUtils.zip(parentPath, zipFilePath); LOGGER.info("【压缩】分批次打包文件.<END>");
} catch (Exception e) { return uploadResultInfos;
LOGGER.error("【压缩】压缩失败,<ERROR>:" + e.getMessage(), e); }
throw new FileException(FileException.ZIP_ERROR, "压缩失败!");
}
// 上传文件到服务器中
UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, zipName);
// 删除产生的文件
FileUtils.deleteDirectory(parentPath);
FileUtils.deleteFile(zipFilePath);
LOGGER.info("【压缩】压缩文件.<END>");
return uploadResultInfo;
}
/** /**
* @Desc ZIP文件解压 * 压缩文件
* @param zipPath *
* ZIP文件目录 * @param fileUrlList String[0]=文件名称, String[1]=文件地址
* @param destDir * @param zipName 压缩包的名称
* 解压目录 * @return
* @throws Exception * @throws BizException
*/ */
private static void unzip(String zipPath, String destDir) throws Exception { public static UploadResultInfo zip(List<String[]> fileUrlList, String zipName) throws BizException {
try { LOGGER.info("【压缩】压缩文件.<START>");
Project p = new Project(); if (ListUtils.isEmpty(fileUrlList)) {
Expand e = new Expand(); return null;
e.setProject(p); }
e.setSrc(new File(zipPath)); zipName = FileUtils.formatName(zipName);
e.setOverwrite(false); String tempZipName = zipName + "_" + LocalDateUtils.getYmdhmss();
e.setDest(new File(destDir)); String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip";
e.setEncoding("gbk"); // 检查临时文件夹是否存在,不存在就创建
e.execute(); String fileFolderPath = FILE_LOCAL_PATH + tempZipName;
} catch (Exception e) { FileUtils.isDir(fileFolderPath);
throw e; UploadResultInfo uploadResultInfo = null;
} try {
} // 下载文件到文件夹中
int idx = 1;
for (String[] files : fileUrlList) {
String fileType = FileUtils.getFileType(files[1]);
String fileName = FileUtils.formatName(files[0]);
String downloadLocalPath = fileFolderPath + "/" + fileName + "_" + idx + "." + fileType;
FileUtils.downloadFileFromUrl(files[1], downloadLocalPath);
idx++;
}
// 检查压缩包临时文件夹是否存在,不存在就创建
FileUtils.isDir(ZIP_FILE_PATH);
CompressUtils.zip(fileFolderPath, zipFilePath);
// 上传文件到服务器中
uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, zipName);
uploadResultInfo.setFileName(zipName);
} catch (Exception e) {
LOGGER.error("【压缩】压缩失败,<ERROR>:" + e.getMessage(), e);
throw new FileException(FileException.ZIP_ERROR, "压缩失败!");
} finally {
// 删除产生的文件
FileUtils.deleteDirectory(fileFolderPath);
FileUtils.deleteFile(zipFilePath);
}
LOGGER.info("【压缩】压缩文件.<END>");
return uploadResultInfo;
}
/** /**
* @Desc rar文件解压 * 压缩文件(带目录)
* @param rarPath *
* rar路径 * @param catalogFiles key : 目录名 String[0]=文件名称, String[1]=文件地址
* @param destDir * @param zipName
* 解压到的文件夹 * @return
* @throws Exception * @throws BizException
*/ */
public static void unrar(String rarPath, String destDir) throws Exception { public static UploadResultInfo zipByCatalog(Map<String, List<String[]>> catalogFiles, String zipName)
if (!rarPath.toLowerCase().endsWith(".rar")) { throws BizException {
throw new Exception("非rar文件!"); LOGGER.info("【压缩】压缩文件.<START>");
} if (MapUtils.isEmpty(catalogFiles)) {
File dstDiretory = new File(destDir); return null;
if (!dstDiretory.exists()) { }
dstDiretory.mkdirs(); zipName = FileUtils.formatName(zipName);
} String tempZipName = zipName + "_" + UUIDUitl.generateString(12);
Archive a = new Archive(new File(rarPath)); String parentPath = FILE_LOCAL_PATH + tempZipName;
if (a != null) { FileUtils.isDir(parentPath);
FileHeader fh = a.nextFileHeader(); for (String catalog : catalogFiles.keySet()) {
while (fh != null) { String downloadPath;
String fileName = fh.getFileNameW().isEmpty() ? fh.getFileNameString() : fh.getFileNameW(); // 检查临时文件夹是否存在,不存在就创建
if (fh.isDirectory()) { if (!StringUtil.isEmpty(catalog)) {
File fol = new File(destDir + File.separator + fileName); String catalogFolderPath = parentPath + "/" + catalog;
fol.mkdirs(); FileUtils.isDir(catalogFolderPath);
} else { downloadPath = catalogFolderPath;
File out = new File(destDir + File.separator + fileName.trim()); } else {
if (!out.exists()) { downloadPath = parentPath;
if (!out.getParentFile().exists()) { }
out.getParentFile().mkdirs(); List<String[]> fileUrlList = catalogFiles.get(catalog);
} // 下载文件到文件夹中
out.createNewFile(); int idx = 1;
} for (String[] files : fileUrlList) {
FileOutputStream os = new FileOutputStream(out); String fileType = FileUtils.getFileType(files[1]);
a.extractFile(fh, os); String fileName = FileUtils.formatName(files[0]);
os.close(); String downloadLocalPath = downloadPath + "/" + fileName + "_" + idx + "." + fileType;
} FileUtils.downloadFileFromUrl(files[1], downloadLocalPath);
fh = a.nextFileHeader(); idx++;
} }
a.close(); }
} // 检查压缩包临时文件夹是否存在,不存在就创建
} FileUtils.isDir(ZIP_FILE_PATH);
String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip";
try {
CompressUtils.zip(parentPath, zipFilePath);
} catch (Exception e) {
LOGGER.error("【压缩】压缩失败,<ERROR>:" + e.getMessage(), e);
throw new FileException(FileException.ZIP_ERROR, "压缩失败!");
}
// 上传文件到服务器中
UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, zipName);
// 删除产生的文件
FileUtils.deleteDirectory(parentPath);
FileUtils.deleteFile(zipFilePath);
LOGGER.info("【压缩】压缩文件.<END>");
return uploadResultInfo;
}
/** /**
* @Desc 解压缩文件 * @param zipPath ZIP文件目录
* @param zip或者rar文件路径 * @param destDir 解压目录
* @param 解压目录 * @throws Exception
* @throws Exception * @Desc ZIP文件解压
*/ */
public static void deCompress(String sourceFile, String destDir) throws Exception { private static void unzip(String zipPath, String destDir) throws Exception {
// 保证文件夹路径最后是"/"或者"\" try {
char lastChar = destDir.charAt(destDir.length() - 1); Project p = new Project();
if (lastChar != '/' && lastChar != '\\') { Expand e = new Expand();
destDir += File.separator; e.setProject(p);
} e.setSrc(new File(zipPath));
// 根据类型,进行相应的解压缩 e.setOverwrite(false);
String type = sourceFile.substring(sourceFile.lastIndexOf(".") + 1).toLowerCase(); e.setDest(new File(destDir));
if (type.equals("zip")) { e.setEncoding("gbk");
unzip(sourceFile, destDir); e.execute();
} else if (type.equals("rar")) { } catch (Exception e) {
unrar(sourceFile, destDir); throw e;
} else { }
throw new Exception("只支持zip和rar格式的压缩包!"); }
}
}
/** /**
* @Desc 压缩zip文件 @param inputFilename 待压缩的文件名称或文件夹路径名称 @param zipFilename * @param rarPath rar路径
* 压缩后的文件完整的路径名称 @throws * @param destDir 解压到的文件夹
*/ * @throws Exception
public static void zip(String inputFilename, String zipFilename) throws IOException { * @Desc rar文件解压
File inputFile = new File(inputFilename); */
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilename)); public static void unrar(String rarPath, String destDir) throws Exception {
try { if (!rarPath.toLowerCase().endsWith(".rar")) {
compress(inputFile, out); throw new Exception("非rar文件!");
// zip(inputFile, out, ""); }
} catch (Exception e) { File dstDiretory = new File(destDir);
throw e; if (!dstDiretory.exists()) {
} finally { dstDiretory.mkdirs();
out.close(); }
} Archive a = new Archive(new File(rarPath));
} if (a != null) {
FileHeader fh = a.nextFileHeader();
while (fh != null) {
String fileName = fh.getFileNameW().isEmpty() ? fh.getFileNameString() : fh.getFileNameW();
if (fh.isDirectory()) {
File fol = new File(destDir + File.separator + fileName);
fol.mkdirs();
} else {
File out = new File(destDir + File.separator + fileName.trim());
if (!out.exists()) {
if (!out.getParentFile().exists()) {
out.getParentFile().mkdirs();
}
out.createNewFile();
}
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
os.close();
}
fh = a.nextFileHeader();
}
a.close();
}
}
/** /**
* 压缩方法 * @param sourceFile zip或者rar文件路径
* * @param destDir 解压目录
* @param inputFile * @throws Exception
* @param out * @Desc 解压缩文件
* @param base */
* @throws IOException public static void deCompress(String sourceFile, String destDir) throws Exception {
*/ // 保证文件夹路径最后是"/"或者"\"
@SuppressWarnings("unused") char lastChar = destDir.charAt(destDir.length() - 1);
private static void zip(File inputFile, ZipOutputStream out, String base) throws IOException { if (lastChar != '/' && lastChar != '\\') {
if (inputFile.isDirectory()) { destDir += File.separator;
File[] inputFiles = inputFile.listFiles(); }
if (!base.equals("")) // 根据类型,进行相应的解压缩
out.putNextEntry(new ZipEntry(base + "/")); String type = sourceFile.substring(sourceFile.lastIndexOf(".") + 1).toLowerCase();
base = base.length() == 0 ? "" : base + "/"; if (type.equals("zip")) {
for (int i = 0; i < inputFiles.length; i++) { unzip(sourceFile, destDir);
zip(inputFiles[i], out, base + inputFiles[i].getName()); } else if (type.equals("rar")) {
} unrar(sourceFile, destDir);
} else { } else {
if (base.length() > 0) { throw new Exception("只支持zip和rar格式的压缩包!");
out.putNextEntry(new ZipEntry(base)); }
} else { }
out.putNextEntry(new ZipEntry(inputFile.getName()));
}
FileInputStream in = new FileInputStream(inputFile);
try {
int c;
byte[] by = new byte[1024];
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
} catch (IOException e) {
throw e;
} finally {
in.close();
}
}
}
/** /**
* 按照原路径的类型就行压缩。文件路径直接把文件压缩, * @Desc 压缩zip文件 @param inputFilename 待压缩的文件名称或文件夹路径名称 @param zipFilename
* * 压缩后的文件完整的路径名称 @throws
* @param src */
* @param zos public static void zip(String inputFilename, String zipFilename) throws IOException {
* @param baseDir File inputFile = new File(inputFilename);
*/ ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilename));
private static void compress(File src, ZipOutputStream zos) { try {
compressbyType(src, zos, "", true); compress(inputFile, out);
} // zip(inputFile, out, "");
} catch (Exception e) {
throw e;
} finally {
out.close();
}
}
/** /**
* 按照原路径的类型就行压缩。文件路径直接把文件压缩, * 压缩方法
* *
* @param src * @param inputFile
* @param zos * @param out
* @param baseDir * @param base
*/ * @throws IOException
private static void compressbyType(File src, ZipOutputStream zos, String baseDir, boolean isFirst) { */
if (!src.exists()) @SuppressWarnings("unused")
return; private static void zip(File inputFile, ZipOutputStream out, String base) throws IOException {
// 判断文件是否是文件,如果是文件调用compressFile方法,如果是路径,则调用compressDir方法; if (inputFile.isDirectory()) {
if (src.isFile()) { File[] inputFiles = inputFile.listFiles();
// src是文件,调用此方法 if (!base.equals(""))
compressFile(src, zos, baseDir); out.putNextEntry(new ZipEntry(base + "/"));
} else if (src.isDirectory()) { base = base.length() == 0 ? "" : base + "/";
// src是文件夹,调用此方法 for (int i = 0; i < inputFiles.length; i++) {
compressDir(src, zos, baseDir, isFirst); zip(inputFiles[i], out, base + inputFiles[i].getName());
}
} else {
if (base.length() > 0) {
out.putNextEntry(new ZipEntry(base));
} else {
out.putNextEntry(new ZipEntry(inputFile.getName()));
}
FileInputStream in = new FileInputStream(inputFile);
try {
int c;
byte[] by = new byte[1024];
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
} catch (IOException e) {
throw e;
} finally {
in.close();
}
}
}
} /**
} * 按照原路径的类型就行压缩。文件路径直接把文件压缩,
*
* @param src
* @param zos
*/
private static void compress(File src, ZipOutputStream zos) {
compressbyType(src, zos, "", true);
}
/** /**
* 压缩文件 * 按照原路径的类型就行压缩。文件路径直接把文件压缩,
*/ *
private static void compressFile(File file, ZipOutputStream zos, String baseDir) { * @param src
if (!file.exists()) * @param zos
return; * @param baseDir
try { */
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); private static void compressbyType(File src, ZipOutputStream zos, String baseDir, boolean isFirst) {
ZipEntry entry = new ZipEntry(baseDir + file.getName()); if (!src.exists())
zos.putNextEntry(entry); return;
int count; // 判断文件是否是文件,如果是文件调用compressFile方法,如果是路径,则调用compressDir方法;
byte[] buf = new byte[1024]; if (src.isFile()) {
while ((count = bis.read(buf)) != -1) { // src是文件,调用此方法
zos.write(buf, 0, count); compressFile(src, zos, baseDir);
} } else if (src.isDirectory()) {
bis.close(); // src是文件夹,调用此方法
} catch (Exception e) { compressDir(src, zos, baseDir, isFirst);
}
}
/** }
* 压缩文件夹 }
*/
private static void compressDir(File dir, ZipOutputStream zos, String baseDir, boolean isFirst) {
if (!dir.exists())
return;
File[] files = dir.listFiles();
if (files.length == 0 && !StringUtil.isEmpty(baseDir)) {
try {
zos.putNextEntry(new ZipEntry(baseDir + dir.getName() + File.separator));
} catch (IOException e) {
e.printStackTrace();
}
}
for (File file : files) {
if (isFirst) {
compressbyType(file, zos, baseDir, false);
} else {
compressbyType(file, zos, baseDir + dir.getName() + File.separator, false);
}
}
}
/** /**
* @Desc 压缩zip文件 @param inputFilename 待压缩的文件名称或文件夹路径名称 @param zipFilename * 压缩文件
* 压缩后的文件完整的路径名称 @throws */
*/ private static void compressFile(File file, ZipOutputStream zos, String baseDir) {
public static void zip(String inputFilename, ZipOutputStream out) throws IOException { if (!file.exists())
File inputFile = new File(inputFilename); return;
try { try {
compress(inputFile, out); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
// zip(inputFile, out, ""); ZipEntry entry = new ZipEntry(baseDir + file.getName());
} catch (Exception e) { zos.putNextEntry(entry);
throw e; int count;
} finally { byte[] buf = new byte[1024];
out.close(); while ((count = bis.read(buf)) != -1) {
} zos.write(buf, 0, count);
} }
bis.close();
} catch (Exception e) {
}
}
/**
* 压缩文件夹
*/
private static void compressDir(File dir, ZipOutputStream zos, String baseDir, boolean isFirst) {
if (!dir.exists())
return;
File[] files = dir.listFiles();
if (files.length == 0 && !StringUtil.isEmpty(baseDir)) {
try {
zos.putNextEntry(new ZipEntry(baseDir + dir.getName() + File.separator));
} catch (IOException e) {
e.printStackTrace();
}
}
for (File file : files) {
if (isFirst) {
compressbyType(file, zos, baseDir, false);
} else {
compressbyType(file, zos, baseDir + dir.getName() + File.separator, false);
}
}
}
/**
* @Desc 压缩zip文件 @param inputFilename 待压缩的文件名称或文件夹路径名称 @param zipFilename
* 压缩后的文件完整的路径名称 @throws
*/
public static void zip(String inputFilename, ZipOutputStream out) throws IOException {
File inputFile = new File(inputFilename);
try {
compress(inputFile, out);
// zip(inputFile, out, "");
} catch (Exception e) {
throw e;
} finally {
out.close();
}
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment