java web檔案相關操作
阿新 • • 發佈:2018-11-26
一. 檔案上傳
(1)使用FileUtils.copyInputStreamToFile上傳,若上傳目錄不存在,工具類會幫忙建立目錄
/** * @Title: roadFileAddUpload * @Description: 新增多個檔案上傳功能 * @param myfile * @return * @throws Exception */ @RequestMapping({ "road/roadfileaddupload" }) public String roadFileAddUpload( @RequestParam("attachUp") MultipartFile myfile) throws Exception { String id = this.request.getParameter("id"); //1. 判斷檔案格式是否正確 String filename = myfile.getOriginalFilename(); ConfigUtil conf = ConfigUtil.getInstance(); String rightFiles = conf.getValue("rightFiles"); String[] files = rightFiles.split(","); boolean flag = false; for(String f : files){ if(filename.endsWith(f)){ flag = false; break; } flag = true; } if(flag ){ return "redirect:/test/testFile.action?id=" + id; } //2. 判斷資料庫中是否已有該檔案 // ... //3. 判斷檔案大小是否超過最大大小 String extStr = "";// 檔案字尾 String issueStr = ""; String name = ""; this.uploadSize = Integer .parseInt(this.rb.getString("ATTACHMENT_SIZE")); if (!myfile.isEmpty()) { if (myfile.getSize() > this.uploadSize * 1024 * 1024) { return "redirect:/test/testFile.action?id=" + id; } extStr = FileUtils.getExt(myfile.getOriginalFilename()); name = TimeUtil.getCurrentDate("yyyyMMdd") + myfile.getOriginalFilename(); if (attach == null || attach.equals("")) { issueStr = name; } else { issueStr = attach + ";" + name; } } //4. 儲存新上傳的檔案 String savePath = conf.getValue("SAVE_ATTACHMENT"); //解決上傳中文檔案下載下來檔案無法開啟的問題 logger.info("name: " + name); logger.info("name GB18030: " + new String(name.getBytes("utf-8") , "GB18030")); /*name = new String(name.getBytes("utf-8") , "GB18030");*/ if (!myfile.isEmpty()) { FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File( savePath, name)); //5.更新資料庫中檔名欄位 // ... }//myfile is not empty return "redirect:/test/testFile.action?id=" + id; }
(2) 使用multipartFile.transferTo(newFilePath)上傳檔案,需要提前建立檔案存放目錄
// 批量匯入歷史記錄 @RequestMapping(value = "importRecordList") public ModelAndView importRecordList(HttpServletRequest request, HttpServletResponse response) throws Exception{ ResponseInfo responseInfo = new ResponseInfo(); try { //將當前上下文初始化給 CommonsMutipartResolver (多部分解析器) CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver( request.getSession().getServletContext()); // 判斷是否是多資料段提交格式 if (multipartResolver.isMultipart(request)) { MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request; Iterator<String> iter = multiRequest.getFileNames(); logger.info("iter.hasNext(): "+iter.hasNext()); Integer fileCount = 0; while (iter.hasNext()) { MultipartFile multipartFile = multiRequest.getFile(iter.next()); String fileName = multipartFile.getOriginalFilename(); logger.info("upload filename: " + fileName ); if(fileName == null || fileName.trim().equals("")){ continue; } //20170207 針對IE環境下filename是整個檔案路徑的情況而做以下處理 Integer index = fileName.lastIndexOf("\\"); String newStr = ""; if(index>-1){ newStr = fileName.substring(index+1); }else{ newStr = fileName; } if(!newStr.equals("")){ fileName = newStr; } logger.info("new filename: " + fileName ); if (multipartFile != null) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//設定日期格式 String now = df.format(new Date());// new Date()為獲取當前系統時間 logger.info("now: " + now); String tempPath=System.getProperty("user.dir"); //C:\Users\alibaba\AppData\Local\Temp\tomcat-docbase.8773812282408690471.7001\ logger.info(request.getSession().getServletContext().getRealPath("") ); //null logger.info(request.getSession().getServletContext().getRealPath("../") ); logger.info(System.getProperty("user.dir") );//專案的根路徑 File existPath = new File(tempPath); if (!existPath.exists()) { existPath.mkdirs();//不存在則建立此資料夾 } String absoluteFilePath = existPath.getAbsolutePath(); logger.info("dest absoluteFilePath: " + absoluteFilePath); String path =""; String newFileName = now+"_" + fileName; path = absoluteFilePath + File.separator + newFileName; logger.info("檔案路徑: " + path); //上傳 multipartFile.transferTo(new File(path)); //獲取副檔名 Integer tempIndex = newFileName.lastIndexOf('.'); Integer fileNameLength = newFileName.length(); String extendName = newFileName.substring(tempIndex+1, fileNameLength); logger.info("副檔名: " + extendName); HashMap<String,Object> contentMap = new HashMap<String,Object>(); if(extendName != null && !extendName.equals("")){ contentMap = ExcelReader.read(path,extendName); Boolean success = (Boolean)contentMap.get("success"); if(success.equals(true)){//Excel讀取成功 List<List<Object>> dataList = (List<List<Object>>)contentMap.get("dataList"); if(dataList != null && dataList.size() > 1){ if(dataList.size()-1>Constants.MAX_IMPORT_BATCH_SIZE){ responseInfo.setStatus(false); responseInfo.setMsg("一次匯入數量不得超過" + Constants.MAX_IMPORT_BATCH_SIZE); }else { HashMap<String, Object> result = this.accordService.importRecordList(contentMap); boolean success2 = (boolean) result.get("success"); String msg = (String) result.get("msg"); Integer count = (Integer)result.get("count"); responseInfo.put("count", count); responseInfo.setStatus(success2); responseInfo.setMsg(msg); } }else{ responseInfo.setStatus(false); responseInfo.setMsg("Excel內容為空"); } }else{ responseInfo.setStatus(false); responseInfo.setMsg((String)contentMap.get("msg")); } }else{ responseInfo.setStatus(false); responseInfo.setMsg("輸入的Excel檔案格式不正確"); } //刪除路徑下的檔案 File deleteFile = new File(path); if(deleteFile.exists()) { logger.info("delete file: " + path); deleteFile.delete(); } } fileCount++; }//while logger.info("fileCount: " + fileCount); } }catch (Exception e) { // TODO: handle exception responseInfo.setStatus(false); responseInfo.setMsg("後臺出現異常"); logger.warn("Error: ", e); } response.setContentType("text/html; charset=utf-8"); response.getWriter().write(JSON.toJSONString(responseInfo)); return null; }
二. 檔案下載
@RequestMapping("common/download") public void download(HttpServletRequest request,HttpServletResponse response) throws IOException{ ConfigUtil conf = ConfigUtil.getInstance(); if (FilterUtil.myFilter(request)==false) { session.setAttribute("fileDownload", 0); }else{ String filePath = ""; logger.info("filename1: " + request.getParameter("filename")); //logger.info("filename2: " + new String(request.getParameter("filename").getBytes("ISO8859-1"),"UTF-8")); //logger.info("filename3: " + new String(request.getParameter("filename").getBytes("GB18030"),"UTF-8")); //logger.info("filename4: " + new String(request.getParameter("filename").getBytes("utf-8"),"UTF-8")); //檔名轉碼 20150908 update //String filename = new String(request.getParameter("filename").getBytes("ISO8859-1"),"UTF-8"); String filename = request.getParameter("filename"); //修復路徑遍歷漏洞 filename = FilePath.pathFilter(filename); logger.info("after pathFilter fileName: " + filename); //修正下載漏洞 String rightFiles = conf.getValue("rightFiles"); String[] files = rightFiles.split(","); boolean flag = false; for(String f : files){ if(filename.endsWith(f)){ flag = false; break; } flag = true; } if(flag){ session.setAttribute("fileDownload", 0); return; } if(filename != null && filename.contains("../")){ session.setAttribute("fileDownload", 0); return; } String status = request.getParameter("status")==null?"":request.getParameter("status"); String type = request.getParameter("type"); if(filename == null || type == null){ session.setAttribute("fileDownload", 0); }else if(type.equals("r_csv")){ //csv匯出 filePath = conf.getValue("CSV_EXPORT") + filename; }else if(type.equals("r_attach")){ //附件匯出 filePath = conf.getValue("ATTACHMENT_PATH") + filename; }else{ //模板等檔案下載 filePath = conf.getValue("FILES") + filename; } filePath = filePath.replace("\\","/"); logger.info("Download Path: " + filePath); filePath = new String(filePath.getBytes("utf-8") , "GB18030"); logger.info("Download Path after encoding: " + filePath); //response.setCharacterEncoding("gbk"); response.setContentType("application/octet-stream;charset=utf-8"); //response.addHeader("Content-Disposition","attachment;filename=" + new String(filename.getBytes("utf-8"),"iso-8859-1")); logger.info("filename 1: " + new String(filename.getBytes("utf-8"),"iso-8859-1")); String tempStr = new String(filename.getBytes("utf-8") , "GB18030"); logger.info("filename 2: " + tempStr); logger.info("filename 3: " + new String(tempStr.getBytes("GB18030"),"iso-8859-1")); //20171026 顯式設定下載檔名稱 String fileShowName = request.getParameter("showName"); if(fileShowName != null && !fileShowName.equals("")){ tempStr = new String(fileShowName.getBytes("utf-8") , "GB18030"); } response.addHeader("Content-Disposition","attachment;filename=" + new String(tempStr.getBytes("GB18030"),"iso-8859-1")); OutputStream outp = null; FileInputStream in = null; try{ if(filename.contains("http:")){//url地址 if(!FileUtils.isURLInWhiteList(filename)){//不在白名單裡的域名 return; } HttpURLConnection httpUrl = null; URL url = null; BufferedInputStream bis = null; url = new URL(filename); httpUrl = (HttpURLConnection) url.openConnection(); // 修復漏洞 httpUrl.setInstanceFollowRedirects(false); httpUrl.connect(); bis = new BufferedInputStream(httpUrl.getInputStream()); outp = response.getOutputStream(); byte[] b = new byte[1024]; int i = 0; while((i = bis.read(b)) > 0){ outp.write(b, 0, i); } outp.flush(); outp.close(); httpUrl.disconnect(); bis.close(); outp=null; }else{ in = new FileInputStream(filePath); outp = response.getOutputStream(); byte[] b = new byte[1024]; int i = 0; while((i = in.read(b)) > 0){ outp.write(b, 0, i); } outp.flush(); outp.close(); outp=null; } response.flushBuffer(); logger.info("no error " ); } catch(FileNotFoundException e){ System.out.println("Error!!"); logger.info("FileNotFoundException e: " + e); e.printStackTrace(); session.setAttribute("fileDownload", 0); } finally{ if(in != null){ in.close(); in = null; } if(outp != null){ outp.close(); outp = null; } } } session.setAttribute("fileDownload", 1); }
三. 其他檔案操作(壓縮等)
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* 檔案處理類,壓縮,解壓縮等
*
* @author v-zhuchaoqun
* @create 20121105
*
*/
public class FileUtils extends org.apache.commons.io.FileUtils {
private String filePath; // Zip檔案的路徑
private ZipOutputStream zos; // Zip檔案輸出流
private final int BUFFER = 4096; // 緩衝區大小
private static Logger logger = Logger.getLogger(FileUtils.class.getName());
public FileUtils() {
// Constructor
}
public FileUtils(String filePath) {
// 初始化Zip檔案的路徑
this.filePath = filePath;
// 生成Zip檔案
makeZipFile();
}
/**
* 建立檔案目錄
*
* @param directory
* @param subDirectory
*/
public static void createDirectory(String directory, String subDirectory) {
String dir[];
File fl = new File(directory);
try {
// 如果解壓檔案基本目錄結構不存在,新建
if (subDirectory == "" && fl.exists() != true) {
// System.out.println("*******建立基本目錄結構*******"+directory);
fl.mkdir();
}
// 主要建立子目錄
else if (subDirectory != "") {
dir = subDirectory.replace('\\', '/').split("/");
for (int i = 0; i < dir.length; i++) {
File subFile = new File(directory + File.separator + dir[i]);
if (subFile.exists() == false) {
// System.out.println("*******建立子目錄*******"+directory +
// File.separator + dir[i]);
subFile.mkdir();
}
directory += File.separator + dir[i];
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
/**
* 解壓*.zip格式檔案
*
* @param zipFileName
* 檔名
* @param outputDirectory
* 解壓路徑
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static String extractZip(String zipFileName, String outputDirectory)
throws Exception {
System.out.println(zipFileName);
String fileStr = ""; // log記錄,解壓的檔名
org.apache.tools.zip.ZipFile zipFile = null;
try {
//20160318
zipFile = new org.apache.tools.zip.ZipFile(zipFileName,"GBK");
java.util.Enumeration e = zipFile.getEntries();
org.apache.tools.zip.ZipEntry zipEntry = null;
createDirectory(outputDirectory, "");
while (e.hasMoreElements()) {
zipEntry = (org.apache.tools.zip.ZipEntry) e.nextElement();
logger.info("========== 解壓 ========== "
+ zipEntry.getName());
// fileStr += zipEntry.getName() + "@@";
// 判斷是否為一個資料夾
if (zipEntry.isDirectory()) {
String name = zipEntry.getName().trim();
// 因為後面帶有一個/,所有要去掉
name = name.substring(0, name.length() - 1);
File f = new File(outputDirectory + File.separator + name);
if (!f.exists()) {
f.mkdir();
}
// System.out.println("*******建立根目錄*******" +
// outputDirectory + File.separator + name);
} else {
String fileName = zipEntry.getName();
fileName = fileName.replace('\\', '/');
fileStr += fileName + "@@";
// 判斷子檔案是否帶有目錄,有建立,沒有寫檔案
if (fileName.indexOf("/") != -1) {
createDirectory(outputDirectory, fileName.substring(0,
fileName.lastIndexOf("/")));
fileName = fileName
.substring(fileName.lastIndexOf("/") + 1);
// fileStr = fileStr + fileName + "\r\n";
}
//20151209 add
String extractPath = outputDirectory + File.separator
+ zipEntry.getName();
//20160318
//File f = new File(new String(extractPath.getBytes("utf-8"), "GB18030"));
File f = new File(encodeForServer(extractPath));
logger.info(outputDirectory + File.separator
+ zipEntry.getName());
logger.info("encodeForServer(extractPath): " + encodeForServer(extractPath));
logger.info("GB18030 extract file: "+ new String(extractPath.getBytes("utf-8")
, "GB18030"));
f.createNewFile();
InputStream in = zipFile.getInputStream(zipEntry);
FileOutputStream out = new FileOutputStream(f);
byte[] by = new byte[1024];
int c;
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
in.close();
out.close();
}
}
} catch (Exception ex) {
ex.printStackTrace();
logger.error(ex.getMessage());
} finally {
zipFile.close();
}
logger.info(fileStr + "\n" + "^^^^^^^^^^ 解壓完成 ^^^^^^^^^^");
return fileStr;
}
/**
* 建立*.zip檔案
*/
public void makeZipFile() {
try {
zos = new ZipOutputStream(new FileOutputStream(filePath));
// 設定ZIP檔案註釋
// String comment = "Make images import *.zip file";
// zos.setComment(comment);
zos.setEncoding("gbk");
// 設定用於後續條目的預設壓縮方法
zos.setMethod(ZipOutputStream.DEFLATED);
} catch (FileNotFoundException e) {
logger.error("[生成Zip檔案失敗] " + e);
}
}
/**
* 將目標資料夾寫入Zip
*
* @param targetFolder
* 需要壓縮的檔案(目錄)
* @return 寫入成功,返回true;失敗,返回false
*/
public boolean packToZip(String targetFolder) {
try {
File folder = new File(targetFolder + "/");
if (folder.isDirectory()) {
File[] files = folder.listFiles();
for (File file : files) {
System.out.println("Files in folder: " + file.getName());
// 目錄下的檔案新增到*.zip
writeZipFile(targetFolder + "/" + file.getName());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Fail");
return false;
} finally {
closeZipOutputStream();
}
return true;
}
/**
* 將一個檔案寫入*.zip
*
* @param targetFile
* 目標檔案
* @return 寫入成功,返回true;失敗,返回false
*/
public boolean writeZipFile(String targetFile) {
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
// 建立檔案輸入流物件
fis = new FileInputStream(targetFile);
bis = new BufferedInputStream(fis, BUFFER);
// 獲取目錄結構
String[] array = targetFile.replace("\\", "/").split("/");
int length = array.length;
String str = "";
if (array[length - 2] == null || array[length - 2].equals(""))
str = "";
else
str = array[length - 2] + "/";
logger.info("File to Zip: " + str + array[length - 1]
+ ", length: " + targetFile.length());
//20151102 為防止壓縮檔案中檔案亂碼
String tempStr = str + array[length - 1];
tempStr = encodeForServer(tempStr);
logger.info("encodeForServer tempStr: " + tempStr);
logger.info("tempStr2: " + new String(tempStr.getBytes("GB18030"),"utf-8"));
ZipEntry entry = new ZipEntry(tempStr);
//ZipEntry entry = new ZipEntry(str + array[length - 1])
// 設定壓縮檔案大小
entry.setCompressedSize(2048);
zos.putNextEntry(entry);
int count;
byte[] buffer = new byte[BUFFER];
while ((count = bis.read(buffer, 0, BUFFER)) != -1) {
zos.write(buffer, 0, count);
}
} catch (Exception e) {
logger.warn("[向Zip中新增檔案失敗] " + e);
} finally {
try {
fis.close();
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return true;
}
/**
* 關閉Zip輸出流
*/
public void closeZipOutputStream() {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
logger.error("[關閉Zip輸出流錯誤] " + e);
}
}
/**
* 複製檔案到指定路徑
*
* @param fromPath
* 原路徑(包含檔名)
* @param destPath
* 目標路徑
* @return
* @throws UnsupportedEncodingException
*/
// public boolean CopyFiles(String fromPath, String destPath, String
// filename){
public static boolean CopyFiles(String fromPath, String destPath) throws UnsupportedEncodingException {
System.out.println("From:" + fromPath + " to:" + destPath);
String srcPath = fromPath.replace("\\", "/");
String[] srcArr = srcPath.split("/");
// System.out.println("filePath:" + srcPath.substring(0,
// srcPath.lastIndexOf("/")));
String filename = srcArr[srcArr.length - 1];
//20151111 處理從使用者反饋回來的附件 暫時還沒拷貝到高快伺服器上
String str = filename.trim();
String[] strArr = str.split("/");
if(strArr.length>1 && strArr[0].equals("http:")){//使用者反饋回來的附件
logger.info("filename - " + filename + " cannot download");
return false;
}
// System.out.println("filename:" + filename);
String ext = "";
try {
if(filename.lastIndexOf(".")<0){
logger.info("filename - " + filename + " : 無法獲取副檔名");
return false;
}
ext = filename.substring(filename.lastIndexOf("."),
filename.length());
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return false;
}
String tgtPath = destPath.replace("\\", "/");
String[] destArr = tgtPath.split("/");
String newfilename = "";
if (destArr[destArr.length - 1].indexOf(".") == -1) {
newfilename = srcArr[srcArr.length - 1];
tgtPath = destPath.replace("\\", "/") + newfilename;
} else { // 包含檔名,則重新命名
newfilename = destArr[destArr.length - 1].substring(0,
destArr[destArr.length - 1].lastIndexOf(".")) + ext;
tgtPath = destPath.replace("\\", "/");
tgtPath = tgtPath.substring(0, tgtPath.lastIndexOf("/") + 1)
+ newfilename;
}
// System.out.println("new filename:" + newfilename);
// System.out.println("Target filename:" + tgtPath);
logger.info("From srcPath: " + srcPath + " to tgtFile: "
+ tgtPath);
//2015092
tgtPath = new String(tgtPath.getBytes("utf-8")
, "GB18030");
logger.info("encoding GB18030 tgtPath: " + tgtPath);
//20151102
srcPath = new String(srcPath.getBytes("utf-8")
, "GB18030");
logger.info("encoding GB18030 srcPath: " + srcPath);
File srcFile = new File(srcPath);
File tgtFile = new File(tgtPath);
// 判讀要複製的檔案是否存在
if (!srcFile.exists()) {
// System.out.println(srcFile.getName() + "原始檔不存在");
return false;
} else {
// System.out.println("原始檔存在");
}
// 建立新檔案
try {
// 若存在同名的檔案
if (tgtFile.exists()) {
tgtFile.delete();
// System.out.println("The existed file has been deleted!");
} else {
// System.out.print("A new file...");
// 建立新檔案
tgtFile.createNewFile();
// System.out.println(" has been created!");
}
} catch (IOException e) {
e.printStackTrace();
logger.error("[建立檔案失敗] " + e);
return false;
}
// 複製檔案
byte[] b = new byte[(int) srcFile.length()];
if (srcFile.isFile()) {
FileInputStream is = null;
FileOutputStream ps = null;
try {
is = new FileInputStream(srcPath.replace("\\", "/"));
ps = new FileOutputStream(tgtPath.replace("\\", "/"));
is.read(b);
ps.write(b);
} catch (Exception e) {
e.printStackTrace();
logger.error("[複製檔案失敗] " + e);
return false;
} finally {
try {
is.close();
ps.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return true;
}
/**
* 導航反饋附件,移動並重命名
*
* @param fromPath
* 源地址
* @param destPath
* 目標地址
* @param filename
* 檔名
*/
public static boolean MoveAndRename(String fromPath, String destPath,
String tag) {
String srcPath = fromPath.replace("\\", "/");
String[] dirArr = srcPath.split("/");
System.out.println("filePath:"
+ srcPath.substring(0, srcPath.lastIndexOf("/")));
// 原檔名
System.out.println("filename:" + dirArr[dirArr.length - 1]);
// 移動檔案的路徑和新檔名
String tgtPath = destPath.replace("\\", "/")
+ dirArr[dirArr.length - 1];
System.out.println("Target filename:" + tgtPath);
System.out.println("From srcPath: " + srcPath + " to tgtFile: "
+ tgtPath);
File srcFile = new File(srcPath);
File tgtFile = new File(destPath);
// 判讀要複製的檔案是否存在
if (!srcFile.exists()) {
System.out.println(srcFile.getName() + "原始檔不存在");
return false;
} else {
System.out.println("原始檔存在");
}
// 建立新檔案
try {
// 若存在同名的檔案
if (tgtFile.exists()) {
tgtFile.delete();
System.out.println("The existed file has been deleted!");
} else {
System.out.print("A new file...");
// 建立新檔案
tgtFile.createNewFile();
System.out.println(" has been created!");
}
} catch (IOException e) {
e.printStackTrace();
logger.error("[建立檔案失敗] " + e);
return false;
}
// 複製檔案
byte[] b = new byte[(int) srcFile.length()];
FileInputStream is = null;
FileOutputStream ps = null;
if (srcFile.isFile()) {
try {
is = new FileInputStream(srcPath.replace("\\", "/"));
ps = new FileOutputStream(tgtPath.replace("\\", "/"));
is.read(b);
ps.write(b);
} catch (Exception e) {
e.printStackTrace();
logger.error("[複製檔案失敗] " + e);
return false;
} finally {
try {
is.close();
ps.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
public static String getExt(String str) {
return str.substring(str.lastIndexOf("."), str.length());
}
// ---------------------------使用者批量上報---------------------------------
/**
*
* Description: 複製一份新的檔案到指定的目錄,如果與目錄內的檔案重名,則重新命名上傳檔案
*
* @param : File f 要被copy的檔案
* @param : String filename 命名copy後文件的名稱
* @param : String path 指定copy檔案的目錄
*/
public static String copyFile(File f, String filename, String path) {// copy一份新的檔案到指定路徑
File ff = new File(path);
if (!ff.exists())
ff.mkdirs();
List li = listFile(ff);
while (li.contains(filename)) {
filename = reFilenameTo(filename);// 假如目錄裡有同名檔案,則重新命名上傳檔名稱
}
String pathfile = path + "/" + filename;
File newfile = new File(pathfile);
copy(f, newfile); // 複製檔案
return filename;
}
/**
* Description: 返回檔案目錄下的所以檔名稱集合
*
* @param : File directory 檔案目錄路徑
* @return: List 包含目錄下所有的檔名稱
*/
public static List listFile(File directory) {
List list = new ArrayList();
File listfile[] = directory.listFiles();
for (int i = 0; i < listfile.length; i++) {
File f = listfile[i];
if (f.isFile())
list.add(f.getName());
}
return list;
}
/**
* Description: 返回檔案目錄下的所以檔名稱集合
*
* @param : String filename 重新命名這個檔名稱,預設在檔名稱末尾加1
* @return: String 檔案新的名稱的字串
*/
public static String reFilenameTo(String filename) {
int index = filename.lastIndexOf(".");
if (index > 0) {
String frontname = filename.substring(0, index);
String behindname = filename.substring(index, filename.length());
return frontname + 1 + behindname;
} else {
return filename + 1;
}
}
/**
* Description: 檔案的複製
*
* @param : File fromFile
* @param : File toFile
*/
public static void copy(File fromFile, File toFile) {
try {
FileChannel srcChannel = new FileInputStream(fromFile).getChannel();
FileChannel dstChannel = new FileOutputStream(toFile).getChannel();
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
srcChannel.close();
dstChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// -------------------------------------------------------------------------------
// 測試域名是否在白名單中
public static boolean isURLInWhiteList(String urlStr) throws MalformedURLException{
URL url = new URL(urlStr);
String host = url.getHost();
logger.info("url: " + urlStr + "; host: " + host);
List<String> validURLArr = Constants.validURLArr;
for(int i=0; i<validURLArr.size(); i++){
if(host.contains(validURLArr.get(i))){
logger.info("in white list");
return true;
}
}
logger.info("not in white list");
return false;
}
public static String encodeForServer(String str) throws UnsupportedEncodingException{
return new String(str.getBytes("utf-8"), "utf-8");
}
public static void main(String[] args) throws Exception {
// 解壓縮測試
//extractZip("D:/test_files/Test4.zip","D:/test_files/Test4"); //路徑後不用加'/'
// 壓縮檔案測試
FileUtils fu = new FileUtils("D:/test_files/ziptarget");
fu.packToZip("D:/test_files/zip1111");
// 檔案移動測試
//FileUtils fu = new FileUtils();
// fu.CopyFiles("e:/tt/","e:\\test\\","123.txt"); //加'/'
//CopyFiles("e:/tt/123.txt", "e:\\road_fbAttachments\\tgtPath");
//20160316 檢視系統編碼
//String encoding = System.getProperty("file.encoding");
// System.out.println("Encoding:" + encoding);
}
}