struts2上傳工具類
package com.midai.util;import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.ListIterator; import java.util.ResourceBundle; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream;
import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/**
- @Description: 文件相關工具類
- @Copyright: Copyright (c)2014-2015
- @author: yue.yan
- @version: $$Rev: 35 $$
- @date: $$Date: 2014-07-25 16:12:49 +0800 (Fri, 25 Jul 2014) $$
- @lastUpdate: $$Author$$
- Modification History:
- Date Author Version Description
/ public class FileUtil { private static final Logger logger = LoggerFactory.getLogger(FileUtil.class); private static final int BUFFER_SIZE = 1024;
/**
* 取得文件的路徑
* @param fileName
* @return String path
*/
public static String getFilePath(String fileName) {
if (StringUtils.isNotBlank(fileName)) {
fileName = fileName.replaceAll("\\\\", "/");
return fileName.substring(0, fileName.lastIndexOf("/"));
}
return "";
}
/**
* 取得文件名(不包括擴展名)
* @param path 文件路徑
* @return String 不包括擴展名的文件名
*/
public static String getFileName(String path) {
if (StringUtils.isNotBlank(path)) {
path = path.replaceAll("\\\\", "/");
if (path.contains(".")) {
return path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
} else {
return path.substring(path.lastIndexOf("/") + 1);
}
}
return "";
}
/**
* 取得包括擴展名的文件名
* @param path 文件路徑
* @return String 包括擴展名的文件名
*/
public static String getFileNameWithExtension(String path) {
if (StringUtils.isNotBlank(path)) {
path = path.replaceAll("\\\\", "/");
return path.substring(path.lastIndexOf("/") + 1);
}
return "";
}
/**
* 取得文件擴展名
* @param path 文件路徑
* @return String 文件擴展名
*/
public static String getExtension(String path) {
if (StringUtils.isNotBlank(path)) {
return path.substring(path.lastIndexOf(".") + 1).toLowerCase();
}
return "";
}
/**
* <p>單個文件壓縮成zip文件</p>
* @param in 壓縮文件輸入流
* @param out 壓縮文件輸出流
* @param fileName 文件名
* @return true:成功/false:失敗
*/
public static boolean zipFile(InputStream in, OutputStream out, String fileName) {
try {
ZipOutputStream gzout = new ZipOutputStream(out);
ZipEntry entry = new ZipEntry(fileName);
gzout.putNextEntry( entry );
byte[] buf=new byte[BUFFER_SIZE];
int num;
while ((num=in.read(buf)) != -1) {
gzout.write(buf,0,num);
}
gzout.close();
in.close();
}catch(IOException e) {
logger.error(e.getMessage());
return false;
}
return true;
}
/**
* <p>多文件壓縮成zip文件</p>
* @param files 待壓縮文件
* @param out 壓縮文件輸出流
* @return true:成功/false:失敗
*/
public static boolean zipFile(List<File> files, OutputStream out) {
try {
ZipOutputStream gzout = new ZipOutputStream(out);
FileInputStream in;
byte[] buf;
int num;
if (files != null) {
for (File oneFile : files) {
if (!(oneFile.exists() && oneFile.canRead())) continue;
in = new FileInputStream(oneFile);
gzout.putNextEntry(new ZipEntry(oneFile.getName()));
buf=new byte[BUFFER_SIZE];
while ((num=in.read(buf)) != -1) {
gzout.write(buf,0,num);
}
in.close();
}
}
gzout.close();
}catch(IOException e) {
logger.error(e.getMessage());
return false;
}
return true;
}
/**
* 解壓ZIP文件
* @param file zip文件
* @return 解壓出來的文件名
*/
public static String unZipFile(File file, String extension) {
try {
ZipFile zipfile = new ZipFile(file);
Enumeration<? extends ZipEntry> en = zipfile.entries();
ZipEntry entry = null;
String fileName = null;
while(en.hasMoreElements()) {
entry = en.nextElement();
if (StringUtils.isNotBlank(extension) && !getExtension(entry.getName()).equals(extension)) {
continue;
}
fileName = entry.getName();
InputStream entryis = zipfile.getInputStream(entry);
RandomAccessFile fos = new RandomAccessFile (file.getPath() + entry.getName(), "rw");
int n;
byte[] bytes = new byte[BUFFER_SIZE];
while((n=entryis.read(bytes)) != -1) {
fos.write(bytes, 0, n);
}
fos.close();
entryis.close();
}
zipfile.close();
return fileName;
} catch (Exception e) {
logger.error(e.getMessage());
}
return null;
}
private static void writeFile(File src, File dst) {
try {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src),
BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
while (in.read(buffer) > 0) {
out.write(buffer);
}
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void writeHtmlFile(File htmlFile, File dst) throws IOException {
FileInputStream fr = new FileInputStream(htmlFile);
InputStreamReader brs = new InputStreamReader(fr,"utf-8");
BufferedReader br = new BufferedReader(brs);
FileOutputStream fos=new FileOutputStream(dst);
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(fos,"UTF8"));
String input = null;
//每讀一行進行一次寫入動作
while(true)
{
input = br.readLine();
if(input == null){
break;
}
bw.write(input);
//newLine()方法寫入與操作系統相依的換行字符,依執行環境當時的OS來決定該輸出那種換行字符
bw.newLine();
}
br.close();
bw.close();
}
private static void writeHtmlFile(String html, File dst) throws IOException {
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(dst, false);
bw = new BufferedWriter(fw);
bw.write(html);
} catch (IOException e) {
e.printStackTrace();
} finally{
bw.close();
fw.close();
}
}
public static String updateFile(File upload,String uploadFileName){
ResourceBundle rb = ResourceBundle.getBundle("init");
String path = rb.getString("picture.path");
Date d = new Date();
//生產環境文件保存路徑
String fileName = d.getTime() + getFileExp(uploadFileName);
//開發環境文件保存路徑
// String savePath="/upload"+"/" + d.getTime() + getFileExp(uploadFileName); //String toSrc = ServletActionContext.getServletContext().getRealPath(savePath); // 使用時間戳作為文件名 String toSrc = path + "/" + fileName ; //生產環境文件保存路徑 File f = new File(path); //開發環境文件保存路徑 // File f = new File(ServletActionContext.getServletContext().getRealPath("upload")); logger.info("======================================"+toSrc+"====================="); // 創建文件夾 if (!f.exists()) { f.mkdirs(); }
File toFile = new File(toSrc);
writeFile(upload, toFile);
return fileName;
}
//此方法可上傳
public static String updateWWWFile(File upload,String uploadFileName, String dir){
ResourceBundle rb = ResourceBundle.getBundle("init");
//String path = rb.getString("www.picture.path");
String localPath = rb.getString("www.picture.path");
Date d = new Date();
//生產環境文件保存路徑
String fileName = d.getTime() + getFileExp(uploadFileName);
//開發環境文件保存路徑
// String savePath="/upload"+"/" + d.getTime() + getFileExp(uploadFileName); //String toSrc = ServletActionContext.getServletContext().getRealPath(savePath); // 使用時間戳作為文件名 if (StringUtils.isNotEmpty(dir)) { localPath +="/" + dir ; } String toSrc = localPath + "/" + fileName ; //生產環境文件保存路徑 File f = new File(localPath); //開發環境文件保存路徑 // File f = new File(ServletActionContext.getServletContext().getRealPath("upload")); logger.info("======================================"+toSrc+"====================="); // 創建文件夾 if (!f.exists()) { f.mkdirs(); }
File toFile = new File(toSrc);
writeFile(upload, toFile);
return fileName;
}
//222
public static String updateWWWHtmlFile(File upload,String uploadFileName, String dir) throws IOException{
ResourceBundle rb = ResourceBundle.getBundle("init");
String path = rb.getString("www.picture.path");
Date d = new Date();
//生產環境文件保存路徑
String fileName = d.getTime() + ".html";
//開發環境文件保存路徑
// String savePath="/upload"+"/" + d.getTime() + getFileExp(uploadFileName); //String toSrc = ServletActionContext.getServletContext().getRealPath(savePath); // 使用時間戳作為文件名 if (StringUtils.isNotEmpty(dir)) { path +="/" + dir ; } String toSrc = path + "/" + fileName ; //生產環境文件保存路徑 File f = new File(path);
//開發環境文件保存路徑
// File f = new File(ServletActionContext.getServletContext().getRealPath("upload")); logger.info("======================================"+toSrc+"====================="); // 創建文件夾 if (!f.exists()) { f.mkdirs(); }
File toFile = new File(toSrc);
writeHtmlFile(upload, toFile);
return fileName;
}
public static String updateWWWHtmlFile(String htmlTitle,String htmlContents, String dir) throws IOException{
ResourceBundle rb = ResourceBundle.getBundle("init");
String path = rb.getString("www.picture.path");
Date d = new Date();
//生產環境文件保存路徑
String fileName = d.getTime() + ".html";
//開發環境文件保存路徑
// String savePath="/upload"+"/" + d.getTime() + getFileExp(uploadFileName); //String toSrc = ServletActionContext.getServletContext().getRealPath(savePath); // 使用時間戳作為文件名 if (StringUtils.isNotEmpty(dir)) { path +="/" + dir ; } String toSrc = path + "/" + fileName ; //生產環境文件保存路徑 File f = new File(path);
Document doc = Jsoup.parseBodyFragment(htmlContents);
Elements objectEles = doc.getElementsByTag("object");
if(objectEles != null){
ListIterator<Element> objectElesList = objectEles.listIterator();
if(objectElesList.hasNext()){
Element objectEle = objectElesList.next();
if(!"video".equals(objectEle.parent().tagName())){
Element embedEle = objectEle.getElementsByTag("embed").get(0);
String objectHtml = objectEle.outerHtml();
String src = embedEle.attr("src");
String width = objectEle.attr("width");
String height = objectEle.attr("height");
String videoUrl = "";
if(StringUtils.isNotEmpty(src) && src.contains("?") && src.contains("=")){
videoUrl = src.split("\\?")[1].split("\\=")[1];
}else if(!src.contains("\\?")){
videoUrl = src;
}
StringBuffer sb = new StringBuffer();
sb.append("<video controls='controls' width='"+width+"' height='"+height+"' preload='auto' >");
sb.append("<source allowfullscreen='true' quality='high' src='"+videoUrl+"' type='video/mp4'/>");
sb.append(objectHtml);
sb.append("您的瀏覽器不支持此種視頻格式。");
sb.append("</video>");
objectEle.after(sb.toString()).nextElementSibling();
// Element videoEle = objectEle.after(sb.toString()).nextElementSibling(); // videoEle.attr("preload","none").attr("poster","http://www.feiliu.com/zt/img/20120417/img01.jpg"); // videoEle.append(objectHtml); // videoEle.appendText("您的瀏覽器不支持此種視頻格式。"); objectEle.remove(); }else{ Element videoEle = objectEle.parent(); videoEle.attr("preload", "auto"); // videoEle.attr("autoplay", "autoplay"); }
}
}
String html = doc.body().html();
StringBuffer sb = new StringBuffer("");
sb.append("<!DOCTYPE html>");
sb.append("<html>");
sb.append("<head>");
sb.append("<title>"+htmlTitle+"</title>");
sb.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
sb.append("</head>");
sb.append("<body>");
sb.append(html);
sb.append("</body>");
sb.append("</html>");
//開發環境文件保存路徑
// File f = new File(ServletActionContext.getServletContext().getRealPath("upload")); logger.info("======================================"+toSrc+"====================="); // 創建文件夾 if (!f.exists()) { f.mkdirs(); }
File toFile = new File(toSrc);
writeHtmlFile(sb.toString(), toFile);
return fileName;
}
// 上傳文件的文件名
private static String getFileExp(String name) {
int pos = name.lastIndexOf(".");
return name.substring(pos);
}
} </pre>
/** * Copyright © 2012-2013 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.midai.util; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 文件操作工具類 * 實現文件的創建、刪除、復制、壓縮、解壓以及目錄的創建、刪除、復制、壓縮解壓等功能 * @author ThinkGem * @version 2013-06-21 */ public class FileUtils extends org.apache.commons.io.FileUtils { private static Logger log = LoggerFactory.getLogger(FileUtils.class); /** * 復制單個文件,如果目標文件存在,則不覆蓋 * @param srcFileName 待復制的文件名 * @param descFileName 目標文件名 * @return 如果復制成功,則返回true,否則返回false */ public static boolean copyFile(String srcFileName, String descFileName) { return FileUtils.copyFileCover(srcFileName, descFileName, false); } /** * 復制單個文件 * @param srcFileName 待復制的文件名 * @param descFileName 目標文件名 * @param coverlay 如果目標文件已存在,是否覆蓋 * @return 如果復制成功,則返回true,否則返回false */ public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); // 判斷源文件是否存在 if (!srcFile.exists()) { log.debug("復制文件失敗,源文件 " + srcFileName + " 不存在!"); return false; } // 判斷源文件是否是合法的文件 else if (!srcFile.isFile()) { log.debug("復制文件失敗," + srcFileName + " 不是一個文件!"); return false; } File descFile = new File(descFileName); // 判斷目標文件是否存在 if (descFile.exists()) { // 如果目標文件存在,并且允許覆蓋 if (coverlay) { log.debug("目標文件已存在,準備刪除!"); if (!FileUtils.delFile(descFileName)) { log.debug("刪除目標文件 " + descFileName + " 失敗!"); return false; } } else { log.debug("復制文件失敗,目標文件 " + descFileName + " 已存在!"); return false; } } else { if (!descFile.getParentFile().exists()) { // 如果目標文件所在的目錄不存在,則創建目錄 log.debug("目標文件所在的目錄不存在,創建目錄!"); // 創建目標文件所在的目錄 if (!descFile.getParentFile().mkdirs()) { log.debug("創建目標文件所在的目錄失敗!"); return false; } } } // 準備復制文件 // 讀取的位數 int readByte = 0; InputStream ins = null; OutputStream outs = null; try { // 打開源文件 ins = new FileInputStream(srcFile); // 打開目標文件的輸出流 outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; // 一次讀取1024個字節,當readByte為-1時表示文件已經讀取完畢 while ((readByte = ins.read(buf)) != -1) { // 將讀取的字節流寫入到輸出流 outs.write(buf, 0, readByte); } log.debug("復制單個文件 " + srcFileName + " 到" + descFileName + "成功!"); return true; } catch (Exception e) { log.debug("復制文件失敗:" + e.getMessage()); return false; } finally { // 關閉輸入輸出流,首先關閉輸出流,然后再關閉輸入流 if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } } /** * 復制整個目錄的內容,如果目標目錄存在,則不覆蓋 * @param srcDirName 源目錄名 * @param descDirName 目標目錄名 * @return 如果復制成功返回true,否則返回false */ public static boolean copyDirectory(String srcDirName, String descDirName) { return FileUtils.copyDirectoryCover(srcDirName, descDirName, false); } /** * 復制整個目錄的內容 * @param srcDirName 源目錄名 * @param descDirName 目標目錄名 * @param coverlay 如果目標目錄存在,是否覆蓋 * @return 如果復制成功返回true,否則返回false */ public static boolean copyDirectoryCover(String srcDirName, String descDirName, boolean coverlay) { File srcDir = new File(srcDirName); // 判斷源目錄是否存在 if (!srcDir.exists()) { log.debug("復制目錄失敗,源目錄 " + srcDirName + " 不存在!"); return false; } // 判斷源目錄是否是目錄 else if (!srcDir.isDirectory()) { log.debug("復制目錄失敗," + srcDirName + " 不是一個目錄!"); return false; } // 如果目標文件夾名不以文件分隔符結尾,自動添加文件分隔符 String descDirNames = descDirName; if (!descDirNames.endsWith(File.separator)) { descDirNames = descDirNames + File.separator; } File descDir = new File(descDirNames); // 如果目標文件夾存在 if (descDir.exists()) { if (coverlay) { // 允許覆蓋目標目錄 log.debug("目標目錄已存在,準備刪除!"); if (!FileUtils.delFile(descDirNames)) { log.debug("刪除目錄 " + descDirNames + " 失敗!"); return false; } } else { log.debug("目標目錄復制失敗,目標目錄 " + descDirNames + " 已存在!"); return false; } } else { // 創建目標目錄 log.debug("目標目錄不存在,準備創建!"); if (!descDir.mkdirs()) { log.debug("創建目標目錄失敗!"); return false; } } boolean flag = true; // 列出源目錄下的所有文件名和子目錄名 File[] files = srcDir.listFiles(); for (int i = 0; i < files.length; i++) { // 如果是一個單個文件,則直接復制 if (files[i].isFile()) { flag = FileUtils.copyFile(files[i].getAbsolutePath(), descDirName + files[i].getName()); // 如果拷貝文件失敗,則退出循環 if (!flag) { break; } } // 如果是子目錄,則繼續復制目錄 if (files[i].isDirectory()) { flag = FileUtils.copyDirectory(files[i] .getAbsolutePath(), descDirName + files[i].getName()); // 如果拷貝目錄失敗,則退出循環 if (!flag) { break; } } } if (!flag) { log.debug("復制目錄 " + srcDirName + " 到 " + descDirName + " 失敗!"); return false; } log.debug("復制目錄 " + srcDirName + " 到 " + descDirName + " 成功!"); return true; } /** * * 刪除文件,可以刪除單個文件或文件夾 * * @param fileName 被刪除的文件名 * @return 如果刪除成功,則返回true,否是返回false */ public static boolean delFile(String fileName) { File file = new File(fileName); if (!file.exists()) { log.debug(fileName + " 文件不存在!"); return true; } else { if (file.isFile()) { return FileUtils.deleteFile(fileName); } else { return FileUtils.deleteDirectory(fileName); } } } /** * * 刪除單個文件 * * @param fileName 被刪除的文件名 * @return 如果刪除成功,則返回true,否則返回false */ public static boolean deleteFile(String fileName) { File file = new File(fileName); if (file.exists() && file.isFile()) { if (file.delete()) { log.debug("刪除單個文件 " + fileName + " 成功!"); return true; } else { log.debug("刪除單個文件 " + fileName + " 失敗!"); return false; } } else { log.debug(fileName + " 文件不存在!"); return true; } } /** * * 刪除目錄及目錄下的文件 * * @param dirName 被刪除的目錄所在的文件路徑 * @return 如果目錄刪除成功,則返回true,否則返回false */ public static boolean deleteDirectory(String dirName) { String dirNames = dirName; if (!dirNames.endsWith(File.separator)) { dirNames = dirNames + File.separator; } File dirFile = new File(dirNames); if (!dirFile.exists() || !dirFile.isDirectory()) { log.debug(dirNames + " 目錄不存在!"); return true; } boolean flag = true; // 列出全部文件及子目錄 File[] files = dirFile.listFiles(); for (int i = 0; i < files.length; i++) { // 刪除子文件 if (files[i].isFile()) { flag = FileUtils.deleteFile(files[i].getAbsolutePath()); // 如果刪除文件失敗,則退出循環 if (!flag) { break; } } // 刪除子目錄 else if (files[i].isDirectory()) { flag = FileUtils.deleteDirectory(files[i] .getAbsolutePath()); // 如果刪除子目錄失敗,則退出循環 if (!flag) { break; } } } if (!flag) { log.debug("刪除目錄失敗!"); return false; } // 刪除當前目錄 if (dirFile.delete()) { log.debug("刪除目錄 " + dirName + " 成功!"); return true; } else { log.debug("刪除目錄 " + dirName + " 失敗!"); return false; } } /** * 創建單個文件 * @param descFileName 文件名,包含路徑 * @return 如果創建成功,則返回true,否則返回false */ public static boolean createFile(String descFileName) { File file = new File(descFileName); if (file.exists()) { log.debug("文件 " + descFileName + " 已存在!"); return false; } if (descFileName.endsWith(File.separator)) { log.debug(descFileName + " 為目錄,不能創建目錄!"); return false; } if (!file.getParentFile().exists()) { // 如果文件所在的目錄不存在,則創建目錄 if (!file.getParentFile().mkdirs()) { log.debug("創建文件所在的目錄失敗!"); return false; } } // 創建文件 try { if (file.createNewFile()) { log.debug(descFileName + " 文件創建成功!"); return true; } else { log.debug(descFileName + " 文件創建失敗!"); return false; } } catch (Exception e) { e.printStackTrace(); log.debug(descFileName + " 文件創建失敗!"); return false; } } /** * 創建目錄 * @param descDirName 目錄名,包含路徑 * @return 如果創建成功,則返回true,否則返回false */ public static boolean createDirectory(String descDirName) { String descDirNames = descDirName; if (!descDirNames.endsWith(File.separator)) { descDirNames = descDirNames + File.separator; } File descDir = new File(descDirNames); if (descDir.exists()) { log.debug("目錄 " + descDirNames + " 已存在!"); return false; } // 創建目錄 if (descDir.mkdirs()) { log.debug("目錄 " + descDirNames + " 創建成功!"); return true; } else { log.debug("目錄 " + descDirNames + " 創建失敗!"); return false; } } /** * 壓縮文件或目錄 * @param srcDirName 壓縮的根目錄 * @param fileName 根目錄下的待壓縮的文件名或文件夾名,其中*或""表示跟目錄下的全部文件 * @param descFileName 目標zip文件 */ public static void zipFiles(String srcDirName, String fileName, String descFileName) { // 判斷目錄是否存在 if (srcDirName == null) { log.debug("文件壓縮失敗,目錄 " + srcDirName + " 不存在!"); return; } File fileDir = new File(srcDirName); if (!fileDir.exists() || !fileDir.isDirectory()) { log.debug("文件壓縮失敗,目錄 " + srcDirName + " 不存在!"); return; } String dirPath = fileDir.getAbsolutePath(); File descFile = new File(descFileName); try { ZipOutputStream zouts = new ZipOutputStream(new FileOutputStream( descFile)); if ("*".equals(fileName) || "".equals(fileName)) { FileUtils.zipDirectoryToZipFile(dirPath, fileDir, zouts); } else { File file = new File(fileDir, fileName); if (file.isFile()) { FileUtils.zipFilesToZipFile(dirPath, file, zouts); } else { FileUtils .zipDirectoryToZipFile(dirPath, file, zouts); } } zouts.close(); log.debug(descFileName + " 文件壓縮成功!"); } catch (Exception e) { log.debug("文件壓縮失敗:" + e.getMessage()); e.printStackTrace(); } } /** * 將目錄壓縮到ZIP輸出流 * @param dirPath 目錄路徑 * @param fileDir 文件信息 * @param zouts 輸出流 */ public static void zipDirectoryToZipFile(String dirPath, File fileDir, ZipOutputStream zouts) { if (fileDir.isDirectory()) { File[] files = fileDir.listFiles(); // 空的文件夾 if (files.length == 0) { // 目錄信息 ZipEntry entry = new ZipEntry(getEntryName(dirPath, fileDir)); try { zouts.putNextEntry(entry); zouts.closeEntry(); } catch (Exception e) { e.printStackTrace(); } return; } for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { // 如果是文件,則調用文件壓縮方法 FileUtils .zipFilesToZipFile(dirPath, files[i], zouts); } else { // 如果是目錄,則遞歸調用 FileUtils.zipDirectoryToZipFile(dirPath, files[i], zouts); } } } } /** * 將文件壓縮到ZIP輸出流 * @param dirPath 目錄路徑 * @param file 文件 * @param zouts 輸出流 */ public static void zipFilesToZipFile(String dirPath, File file, ZipOutputStream zouts) { FileInputStream fin = null; ZipEntry entry = null; // 創建復制緩沖區 byte[] buf = new byte[4096]; int readByte = 0; if (file.isFile()) { try { // 創建一個文件輸入流 fin = new FileInputStream(file); // 創建一個ZipEntry entry = new ZipEntry(getEntryName(dirPath, file)); // 存儲信息到壓縮文件 zouts.putNextEntry(entry); // 復制字節到壓縮文件 while ((readByte = fin.read(buf)) != -1) { zouts.write(buf, 0, readByte); } zouts.closeEntry(); fin.close(); System.out .println("添加文件 " + file.getAbsolutePath() + " 到zip文件中!"); } catch (Exception e) { e.printStackTrace(); } } } /** * 獲取待壓縮文件在ZIP文件中entry的名字,即相對于跟目錄的相對路徑名 * @param dirPath 目錄名 * @param file entry文件名 * @return */ private static String getEntryName(String dirPath, File file) { String dirPaths = dirPath; if (!dirPaths.endsWith(File.separator)) { dirPaths = dirPaths + File.separator; } String filePath = file.getAbsolutePath(); // 對于目錄,必須在entry名字后面加上"/",表示它將以目錄項存儲 if (file.isDirectory()) { filePath += "/"; } int index = filePath.indexOf(dirPaths); return filePath.substring(index + dirPaths.length()); } public static String getAbsolutePath(String urlPath) { if(StringUtils.isBlank(urlPath)) { return ""; } else { return SpringContextHolder.getRootRealPath() + urlPath.substring(urlPath.indexOf("/", 1), urlPath.length()); } } /** * 將內容寫入文件 * @param content * @param filePath */ public static void writeFile(String content, String filePath) { try { if (FileUtils.createFile(filePath)){ FileWriter fileWriter = new FileWriter(filePath, true); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(content); bufferedWriter.close(); fileWriter.close(); }else{ log.info("生成失敗,文件已存在!"); } } catch (Exception e) { e.printStackTrace(); } } }
package com.midai.action.information; import java.io.File; import java.io.IOException; import java.util.ResourceBundle; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import bsh.StringUtil; import com.midai.action.BaseAction; import com.midai.pojo.Information; import com.midai.service.IInformationService; import com.midai.util.Constants; import com.midai.util.FileUtil; import com.midai.util.SerializeUtils; public class InformationAction extends BaseAction { private static final long serialVersionUID = 1L; @Autowired private IInformationService informationService; private String infoID; private Information info; //舊路徑 private String appImgOldURL; private String pcImgOldURL; private String appHtmlOldURL; private String pcHtmlOldURL; //上傳圖片屬性 private File appImg; private String appImgContentType; private String appImgFileName; private File pcImg; private String pcImgContentType; private String pcImgFileName; private File appHtml; private String appHtmlContentType; private String appHtmlFileName; private File pcHtml; private String pcHtmlContentType; private String pcHtmlFileName; /** * 上傳文件大小驗證 默認為2M * */ public void validateAddInformation(){ if(this.appImg!=null){ if(this.appImg.length()>Constants.MAXSIZE){ this.addFieldError("appImg", "手機端圖片不能超過2M"); } } if(this.pcImg!=null){ if(this.pcImg.length()>Constants.MAXSIZE){ this.addFieldError("pcImg", "電腦端圖片不能超過2M"); } } if(this.appHtml!=null){ if(this.appHtml.length()>Constants.MAXSIZE){ this.addFieldError("appHtml", "手機端網頁不能超過2M"); } } if(this.pcHtml!=null){ if(this.pcHtml.length()>Constants.MAXSIZE){ this.addFieldError("pcHtml", "電腦端網頁不能超過2M"); } } } /** * 添加公司新聞資訊 * @return */ public String addInformation(){ try { if(info==null){ info=new Information(); } ResourceBundle rb = ResourceBundle.getBundle("init"); String path = rb.getString("www.picture.path.read"); String localPath = rb.getString("www.picture.path"); if("1".equals(info.getUpdateFlg())){ if (this.appImg!=null) { String fileName = FileUtil.updateWWWFile(this.appImg,this.appImgFileName,Constants.UPLOAD_INFO_APP_PICTURE); info.setAppImgURL(path+"/"+Constants.UPLOAD_INFO_APP_PICTURE+"/" + fileName); File oldFile = new File(localPath+"/"+Constants.UPLOAD_INFO_APP_PICTURE+"/"+FileUtil.getFileNameWithExtension(appImgOldURL)); if(oldFile.isFile() || oldFile.exists()){ oldFile.delete(); }; }else{ if(StringUtils.isNotEmpty(appImgOldURL)){ info.setAppImgURL(path+"/"+Constants.UPLOAD_INFO_APP_PICTURE+"/"+FileUtil.getFileNameWithExtension(appImgOldURL)); } } if (this.pcImg!=null) { String fileName = FileUtil.updateWWWFile(this.pcImg,this.pcImgFileName,Constants.UPLOAD_INFO_PC_PICTURE); info.setPcImgURL(path+"/"+Constants.UPLOAD_INFO_PC_PICTURE+"/" + fileName); File oldFile = new File(localPath+"/"+Constants.UPLOAD_INFO_PC_PICTURE+"/"+FileUtil.getFileNameWithExtension(pcImgOldURL)); if(oldFile.isFile() || oldFile.exists()){ oldFile.delete(); }; }else{ if(StringUtils.isNotEmpty(pcImgOldURL)){ info.setPcImgURL(path+"/"+Constants.UPLOAD_INFO_PC_PICTURE+"/"+FileUtil.getFileNameWithExtension(pcImgOldURL)); } } if (this.appHtml!=null) { String fileName = FileUtil.updateWWWFile(this.appHtml,this.appHtmlFileName,Constants.UPLOAD_INFO_APP_HTML); info.setAppHtmlURL(path+"/"+Constants.UPLOAD_INFO_APP_HTML+"/" + fileName); File oldFile = new File(localPath+"/"+Constants.UPLOAD_INFO_APP_HTML+"/"+FileUtil.getFileNameWithExtension(appHtmlOldURL)); if(oldFile.isFile() || oldFile.exists()){ oldFile.delete(); }; }else{ if(StringUtils.isNotEmpty(appHtmlOldURL)){ info.setAppHtmlURL(path+"/"+Constants.UPLOAD_INFO_APP_HTML+"/"+FileUtil.getFileNameWithExtension(appHtmlOldURL)); } } if (this.pcHtml!=null) { String fileName = FileUtil.updateWWWFile(this.pcHtml,this.pcHtmlFileName,Constants.UPLOAD_INFO_PC_HTML); info.setPcHtmlURL(path+"/"+Constants.UPLOAD_INFO_PC_HTML+"/" + fileName); File oldFile = new File(localPath+"/"+Constants.UPLOAD_INFO_PC_HTML+"/"+FileUtil.getFileNameWithExtension(pcHtmlOldURL)); if(oldFile.isFile() || oldFile.exists()){ oldFile.delete(); }; }else{ if(StringUtils.isNotEmpty(pcHtmlOldURL)){ info.setPcHtmlURL(path+"/"+Constants.UPLOAD_INFO_PC_HTML+"/"+FileUtil.getFileNameWithExtension(pcHtmlOldURL)); } } informationService.updateInformation(info); }else{ if (this.appImg!=null) { String fileName = FileUtil.updateWWWFile(this.appImg,this.appImgFileName,Constants.UPLOAD_INFO_APP_PICTURE); info.setAppImgURL(path+"/"+Constants.UPLOAD_INFO_APP_PICTURE+"/" + fileName); } if (this.pcImg!=null) { String fileName = FileUtil.updateWWWFile(this.pcImg,this.pcImgFileName,Constants.UPLOAD_INFO_PC_PICTURE); info.setPcImgURL(path+"/"+Constants.UPLOAD_INFO_PC_PICTURE+"/" + fileName); } if (this.appHtml!=null) { String fileName = FileUtil.updateWWWFile(this.appHtml,this.appHtmlFileName,Constants.UPLOAD_INFO_APP_HTML); info.setAppHtmlURL(path+"/"+Constants.UPLOAD_INFO_APP_HTML+"/" + fileName); } if (this.pcHtml!=null) { String fileName = FileUtil.updateWWWFile(this.pcHtml,this.pcHtmlFileName,Constants.UPLOAD_INFO_PC_HTML); info.setPcHtmlURL(path+"/"+Constants.UPLOAD_INFO_PC_HTML+"/" + fileName); } informationService.addInfo(info); } } catch (Exception e) { e.printStackTrace(); } return SUCCESS; } }