File文件工具类
package com.jack.common.utils;
import com.jack.common.config.EConfig;
import com.jack.common.constant.Constant;
import gui.ava.html.image.generator.HtmlImageGenerator;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import sun.misc.BASE64Decoder;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Properties;
/**
* <文件工具类>
*/
public class FileUtils extends org.apache.commons.io.FileUtils {
// Commons Logging instance.
private static Logger log = Logger.getLogger(JsonUtils.class);
/**
* byte缓存大小
*/
private static final int CACHE_SIZE = 100;
/**
* <下载文件>
*
* @param path 文件路径
* @param response HttpServletResponse
* @param filename 显示的文件名
*/
public static void download(String path, HttpServletResponse response, String filename) {
InputStream fis = null;
try {
// path是指欲下载的文件的路径。
File file = new File(path);
// 以流的形式下载文件。
fis = new BufferedInputStream(new FileInputStream(path));
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
fis.close();
download(bytes, response, filename);
} catch (IOException ex) {
ex.printStackTrace();
log.error(ex);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
log.error(e);
}
}
}
}
public static void jsDownload(String path, HttpServletResponse response) {
String fileName = null;
File file = new File(path);
fileName = file.getName();
if (!fileName.equals("")) {
download(path, response, fileName);
}
}
/**
* <下载文件> 输入文件流
*
* @param filename 文件路径
* @param response HttpServletResponse
* @param filename 显示的文件名
*/
public static void downloadInputStream(InputStream inputStream, HttpServletResponse response, String filename) {
try {
// 以流的形式下载文件。
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
inputStream.close();
download(bytes, response, filename);
} catch (IOException ex) {
ex.printStackTrace();
log.error(ex);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
log.error(e);
}
}
}
}
/**
* <下载文件>
*
* @param bytes 需要下载的二进制
* @param response HttpServletResponse
* @param filename 显示的文件名
*/
public static void download(byte[] bytes, HttpServletResponse response, String filename) {
OutputStream toClient = null;
InputStream fis = null;
try {
// 清空response
response.reset();
String contentType = getContentType(filename);
if (!contentType.equals("application/javascript")) {
String disposition = "application/octet-stream".equals(contentType) ? "attachment" : "inline";
// 解决中文乱码
response.setHeader("Content-Disposition",
disposition + ";filename=" + filename);
}
response.addHeader("Content-Length", "" + bytes.length);
toClient = new BufferedOutputStream(response.getOutputStream());
// response.setContentType(contentType);
response.setHeader("Content-Type", contentType);
toClient.write(bytes);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
log.error(ex);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
log.error(e);
}
}
if (toClient != null) {
try {
toClient.flush();
toClient.close();
} catch (IOException e) {
log.error(e);
}
}
}
}
/**
* 根据文件名获取返回类型 ContentType
*
* @param fileName 文件名
* @return ContentType
*/
private static String getContentType(String fileName) {
String result = "application/octet-stream";
if (fileName == null || (!fileName.contains("."))) {
return result;
}
int index = fileName.lastIndexOf(".");
String suffix = fileName.substring(index + 1);
switch (suffix) {
case "png":
result = "image/png";
break;
case "jpg":
case "jpeg":
result = "image/jpeg";
break;
case "mp4":
result = "video/mpeg4";
break;
case "gif":
result = "application/gif";
break;
case "js":
result = "application/javascript";
break;
}
return result;
}
/**
* 将一个文件加载为properties对象
*
* @param filePath 文件路径
* @return properties对象
*/
public static Properties loadProperties(String filePath) {
Properties properties = new Properties();
try {
properties = PropertiesLoaderUtils.loadAllProperties(filePath);
} catch (Exception e) {
log.error(filePath + "is not find!");
}
return properties;
}
/**
* 关闭输出流
*
* @param os 需要关闭的流对象
*/
public static void closeOutputStream(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 关闭输入流
*
* @param is 需要关闭的流对象
*/
public static void closeInputStream(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 文件分布式存储 存储方式 uuId 的hash 算法
*
* @param saveFilePathType 文件存放的目录
* @param fileName 文件名字
* @param suffix 文件后缀 * @param fileScope File类静态变量 跨域参数
* @return
*/
public static String addLocatedFilePath(String saveFilePathType, String fileName, String suffix, String fileScope) {
// 获取uuId 首字母
String fileOne = fileName.substring(0, 1);
// 获取 uuId 的第二个字母
String fileTwo = fileName.substring(1, 2);
// 存放文件的父文件夹
String saveFilePath = saveFilePathType + fileScope + fileOne;
// 存放文件的子文件夹
String saveFileSonPath = saveFilePath + fileScope + Constant.SLASH + fileTwo;
// 创建父文件夹
if (createFileDir(saveFileSonPath)) {
return saveFileSonPath + Constant.SLASH + fileName;
}
return null;
}
/**
* 创建文件夹
*
* @param filePath 文件夹的路径
* @return
*/
public static boolean createFileDir(String filePath) {
File file = new File(filePath);
// 如果文件夹不存在则创建
if (!file.exists() || !file.isDirectory()) {
file.mkdirs();
}
return true;
}
/**
* 根据uuId 获得文件的路径
*
* @param fileName 文件名称
* @param saveFilePathType 获取文件的目录
* @param fileScope File类静态变量 跨域参数
* @return
*/
public static String getFilePath(String saveFilePathType, String fileName, String fileScope) {
if (saveFilePathType != null && fileName != null) {
// 获取uuId 首字母
String fileOne = fileName.substring(0, 1);
// 获取 uuId 的第二个字母
String fileTwo = fileName.substring(1, 2);
// 获取文件的路径
String loaclFilePath = saveFilePathType + fileScope + fileOne + Constant.SLASH + fileTwo;
// 本地文件的目录
if (createFileDir(loaclFilePath)) {
// 获取文件的完整路径
return loaclFilePath + Constant.SLASH + fileName;
}
}
return "";
}
/**
* 将文件从旧地址 copy到新目录
*
* @param oldPath 旧目录
* @param newPath 新目录
* @throws java.io.FileNotFoundException
* @throws java.io.IOException
*/
public static void copyFile(File oldPath, String newPath)
throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream(oldPath);
FileOutputStream fos = new FileOutputStream(newPath);
int len = 0;
byte[] buf = new byte[1024];
while ((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}
/**
* InputStream 转 byte[]
*
* @param inStream
* @return
* @throws java.io.IOException
*/
public static final byte[] input2byte(InputStream inStream)
throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
// buff用于存放循环读取的临时数据
byte[] buff = new byte[CACHE_SIZE];
int rc = 0;
while ((rc = inStream.read(buff, 0, CACHE_SIZE)) > 0) {
swapStream.write(buff, 0, rc);
}
// in_b为转换之后的结果
byte[] in2b = swapStream.toByteArray();
return in2b;
}
/**
* base64Code 转文件输入流
*
* @param base64Code
* @return 文件输入流
* @throws Exception
*/
public static InputStream decoderBase64File(String base64Code)
throws Exception {
base64Code = base64Code.replace("data:image/jpeg;base64,", base64Code);
byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
InputStream sbs = new ByteArrayInputStream(buffer);
return sbs;
}
/**
* 如果文件不存在,则创建新文件
*
* @param filePath
* @return
*/
public static boolean createNewFile(String filePath) {
File file = new File(filePath);
try {
if (!file.exists()) {
File fileDir = file.getParentFile();
if (!fileDir.exists()) {
fileDir.mkdirs();
}
file.createNewFile();
}
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* <将byte数组转换为file对象>
*
* @param byteArray 需要转换为file对象的byte数组
* @param filePath 生成file文件的路径
*/
public static void byteArrayToFile(byte[] byteArray, String filePath) {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
createNewFile(filePath);
}
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(targetFile);
bos = new BufferedOutputStream(fos);
bos.write(byteArray);
bos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 将BufferedImage转换为图片的信息
*
* @param image
* @return
*/
private static byte[] saveToImg(BufferedImage image) {
byte[] buff = null;
try {
ByteArrayOutputStream b = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", b);
buff = b.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return buff;
}
public static byte[] html2Imgage(String html)
throws Exception {
if (html == null || html == "") {
return null;
}
HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
imageGenerator.loadHtml(html);
byte[] buff = imageGenerator.getImgByte("jpg");
return buff;
}
/**
* <将图片>
*
* @param source
* @param targetW
* @param targetH
* @return
*/
public static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
// targetW,targetH分别表示目标长和宽
int type = source.getType();
BufferedImage target = null;
double sx = (double) targetW / source.getWidth();
double sy = (double) targetH / source.getHeight();
// 这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放
// 则将下面的if else语句注释即可
if (sx > sy) {
sx = sy;
targetW = (int) (sx * source.getWidth());
} else {
sy = sx;
targetH = (int) (sy * source.getHeight());
}
if (type == BufferedImage.TYPE_CUSTOM) { // handmade
ColorModel cm = source.getColorModel();
WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH);
boolean alphaPremultiplied = cm.isAlphaPremultiplied();
target = new BufferedImage(cm, raster, alphaPremultiplied, null);
} else
target = new BufferedImage(targetW, targetH, type);
Graphics2D g = target.createGraphics();
// smoother than exlax:
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
g.dispose();
return target;
}
public static final InputStream byte2Input(byte[] buf) {
return new ByteArrayInputStream(buf);
}
//删除文件夹
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath); //删除完里面所有内容
String filePath = folderPath;
filePath = filePath.toString();
File myFilePath = new File(filePath);
myFilePath.delete(); //删除空文件夹
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
System.gc();
delete(temp);
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
delFolder(path + "/" + tempList[i]);//再删除空文件夹
flag = true;
}
}
return flag;
}
private static void delete(File temp) {
boolean res = temp.delete();
int i = 0;
while (i < 5) {
if (!res) {
res = temp.delete();
} else {
break;
}
i++;
}
}
public static String getSaveName(String saveName, String saveNameBak, String suffix) {
String name = saveName.concat("_" + DateUtils.getDateTime(new Date(), DateUtils.DATETIME_PATTERN_DATE)).concat(suffix);
try {
name = java.net.URLEncoder.encode(name, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return saveNameBak.concat(DateUtils.getDateTime(new Date(), DateUtils.DATETIME_PATTERN_DATE).concat(suffix));
}
return name;
}
public static String addPictureFile(String imgStr) {
String suffix = ".jpg";
String fileId = StringUtil.getUUID();
String path = EConfig.getPathPropertiesValue("downFilePath") + fileId + suffix;
byte[] bytes = Base64Util.getByteFromBase64(imgStr);
try {
FileUtils.writeByteArrayToFile(new File(path),
bytes);
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
/**
* <下载文件>
*
* @param path 文件路径
*/
public static byte[] updownload(String path) {
InputStream fis = null;
byte[] bytes = null;
try {
// path是指欲下载的文件的路径。
File file = new File(path);
// 以流的形式下载文件。
fis = new BufferedInputStream(new FileInputStream(path));
bytes = new byte[fis.available()];
fis.read(bytes);
fis.close();
return bytes;
} catch (IOException ex) {
ex.printStackTrace();
log.error(ex);
return bytes;
}
}
/**
* <下载文件>
*
* @param path 文件路径
* @param response HttpServletResponse
* @param filename 显示的文件名(中文)
*/
public static void downloadByChinese(String path, HttpServletResponse response, String filename) {
InputStream fis = null;
try {
// path是指欲下载的文件的路径。
File file = new File(path);
// 以流的形式下载文件。
fis = new BufferedInputStream(new FileInputStream(path));
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
fis.close();
downloadByChinese(bytes, response, filename);
} catch (IOException ex) {
ex.printStackTrace();
log.error(ex);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
log.error(e);
}
}
}
}
/**
* <下载文件>
*
* @param bytes 需要下载的二进制
* @param response HttpServletResponse
* @param filenames 显示的文件名(中文)
*/
public static void downloadByChinese(byte[] bytes, HttpServletResponse response, String filenames) {
OutputStream toClient = null;
InputStream fis = null;
try {
String filename = new String(filenames.getBytes(),"ISO-8859-1");
// 清空response
response.reset();
String contentType = getContentType(filename);
if (!contentType.equals("application/javascript")) {
String disposition = "application/octet-stream".equals(contentType) ? "attachment" : "inline";
// 解决中文乱码
response.setHeader("Content-Disposition",
disposition + ";filename=" + filename);
}
response.addHeader("Content-Length", "" + bytes.length);
toClient = new BufferedOutputStream(response.getOutputStream());
// response.setContentType(contentType);
response.setHeader("Content-Type", contentType);
toClient.write(bytes);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
log.error(ex);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
log.error(e);
}
}
if (toClient != null) {
try {
toClient.flush();
toClient.close();
} catch (IOException e) {
log.error(e);
}
}
}
}
}