前提是知道文件在哪個文件夾下面然后到文件夾下面刪除文件,如果文件夾也需要傳參數需要對下面方法進行改造。
( 需要借助於commons-io.jar和ResourceUtils.java )
1.DeleteFileUtil.java工具類
package com.tyust.common; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; /** * 根據文件的名字到對應的文件夾下面刪除對應的文件 * * @author QiaoLiQiang * @time 2018年2月6日下午2:22:40 */ public class DeleteFileUtil { /** * 刪除文件(因為一個文件可能存在pdf,doc,docx三種格式,因此需要刪除) * * @param fileName * @return */ public static boolean deleteFile(String fileName) { if (fileName == null) { return false; } String dir = ResourcesUtil.getValue("path", "file");// 獲取文件的基本目錄 String baseName = FilenameUtils.getBaseName(fileName);// 獲取文件的基本名字 try { FileUtils.forceDeleteOnExit(new File(dir + baseName + ".pdf")); FileUtils.forceDeleteOnExit(new File(dir + baseName + ".doc")); FileUtils.forceDeleteOnExit(new File(dir + baseName + ".docx")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } /** * 到存放圖片的文件夾下面刪除圖片 * * @param fileName * @return */ public static boolean deletePicture(String fileName) { if (fileName == null) { return false; } String dir = ResourcesUtil.getValue("path", "picture");// 獲取文件圖片的基本目錄 try { FileUtils.forceDeleteOnExit(new File(dir + fileName)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } public static void main(String[] args) { DeleteFileUtil.deleteFile("ef0c4d250561413e9777fb439e8fbc27.doc"); System.out.println("sss"); } }
解釋:
ResourcesUtil是讀取配置文件中的目錄路徑,FilenameUtils(位於commons-io.jar)是獲取傳來的文件的基本名字,文件夾下面根據基本名字刪除pdf、doc、docx文件。
ResourcesUtil.java 讀取.properties文件中的目錄路徑
package com.tyust.common; import java.io.Serializable; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import java.util.Set; /** * 讀取properties文件的工具類 * @author QiaoLiQiang * @time 2018年2月5日下午4:28:18 */ public class ResourcesUtil implements Serializable { private static final long serialVersionUID = -7657898714983901418L; /** * 系統語言環境,默認為中文zh */ public static final String LANGUAGE = "zh"; /** * 系統國家環境,默認為中國CN */ public static final String COUNTRY = "CN"; private static Locale getLocale() { Locale locale = new Locale(LANGUAGE, COUNTRY); return locale; } /** * 根據語言、國家、資源文件名和key名字獲取資源文件值 * * @param language * 語言 * * @param country * 國家 * * @param baseName * 資源文件名 * * @param section * key名字 * * @return 值 */ private static String getProperties(String baseName, String section) { String retValue = ""; try { Locale locale = getLocale(); ResourceBundle rb = ResourceBundle.getBundle(baseName, locale); retValue = (String) rb.getObject(section); } catch (Exception e) { e.printStackTrace(); // TODO 添加處理 } return retValue; } /** * 通過key從資源文件讀取內容 * * @param fileName * 資源文件名 * * @param key * 索引 * * @return 索引對應的內容 */ public static String getValue(String fileName, String key) { String value = getProperties(fileName,key); return value; } public static List<String> gekeyList(String baseName) { Locale locale = getLocale(); ResourceBundle rb = ResourceBundle.getBundle(baseName, locale); List<String> reslist = new ArrayList<String>(); Set<String> keyset = rb.keySet(); for (Iterator<String> it = keyset.iterator(); it.hasNext();) { String lkey = (String)it.next(); reslist.add(lkey); } return reslist; } /** * 通過key從資源文件讀取內容,並格式化 * * @param fileName * 資源文件名 * * @param key * 索引 * * @param objs * 格式化參數 * * @return 格式化后的內容 */ public static String getValue(String fileName, String key, Object[] objs) { String pattern = getValue(fileName, key); String value = MessageFormat.format(pattern, objs); return value; } public static void main(String[] args) { System.out.println(getValue("resources.messages", "101",new Object[]{100,200})); //根據操作系統環境獲取語言環境 /*Locale locale = Locale.getDefault(); System.out.println(locale.getCountry());//輸出國家代碼 System.out.println(locale.getLanguage());//輸出語言代碼s //加載國際化資源(classpath下resources目錄下的messages.properties,如果是中文環境會優先找messages_zh_CN.properties) ResourceBundle rb = ResourceBundle.getBundle("resources.messages", locale); String retValue = rb.getString("101");//101是messages.properties文件中的key System.out.println(retValue); //信息格式化,如果資源中有{}的參數則需要使用MessageFormat格式化,Object[]為傳遞的參數,數量根據資源文件中的{}個數決定 String value = MessageFormat.format(retValue, new Object[]{100,200}); System.out.println(value); */ } }
path.properties
#the directory of environment file to save file=F:/sbgl/file/ picture=F:/sbgl/picture/
最后附一個自己封裝的刪除文件的完整的工具類:
package cn.xm.jwxt.utils; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.util.Locale; import java.util.ResourceBundle; /** * @Author: qlq * @Description 文件處理類 * @Date: 22:59 2018/4/9 */ public class FileHandleUtil { /******S 封裝的讀取properties文件****************/ /** * 系統語言環境,默認為中文zh */ public static final String LANGUAGE = "zh"; /** * 系統國家環境,默認為中國CN */ public static final String COUNTRY = "CN"; private static String getProperties(String baseName, String section) { String retValue = ""; try { Locale locale = new Locale(LANGUAGE, COUNTRY); ResourceBundle rb = ResourceBundle.getBundle(baseName, locale); retValue = (String) rb.getObject(section); } catch (Exception e) { e.printStackTrace(); // TODO 添加處理 } return retValue; } /** * 通過key從資源文件讀取內容 * * @param fileName * 資源文件名 * * @param key * 索引 * * @return 索引對應的內容 */ public static String getValue(String fileName, String key) { String value = getProperties(fileName,key); return value; } /******E 封裝的讀取properties文件****************/ /**********S 保存文件相關操作**************/ /** * 配置虛擬路徑上傳文件到本地磁盤 * @param f 需要上傳的文件 * @param fileName 保存到磁盤的文件名 * @param pathKey 資源文件中的鍵 path.properties */ public static void uploadFileToDisk(File f,String fileName,String pathKey){ //從資源文件中讀取文件的基本目錄 String basePath = ResourcesUtil.getValue("path", pathKey); //獲取文件的后綴 String sufix = FilenameUtils.getExtension(fileName); //獲取文件的前綴 String prefix = FilenameUtils.getBaseName(fileName); //保存到硬盤的文件的完整路徑 String dir = basePath+fileName; try{ InputStream streamIn = new FileInputStream(f); OutputStream streamOut = new FileOutputStream(new File(dir)); int bytesRead=0; byte[] byffer = new byte[8192]; while((bytesRead=streamIn.read(byffer,0,8192))!=-1){ streamOut.write(byffer, 0, bytesRead); } streamIn.close(); streamOut.flush(); streamOut.close(); } catch (IOException e) { e.printStackTrace(); } //如果文件是doc或者docx文件將文件轉為pdf存一份到服務器 if("doc".equals(sufix)||"docx".equals(sufix)){ try { // Word2PdfUtil.word2pdf(dir, basePath+prefix+".pdf"); } catch (Exception e) { e.printStackTrace(); } } } /**********E 保存文件相關操作**************/ /******************S 刪除文件相關操作********/ /** *刪除word(有可能后綴是doc,docx,或者轉換后的pdf文件) * @param propertiesKey path.properties文件中的key(確定目錄) * @param fileName 需要刪除的文件的名字(確定刪除哪個文件) * @return 刪除結果 */ public static boolean deleteWordOrPdfFile(String propertiesKey,String fileName) { if (fileName == null) { return false; } String dir = FileHandleUtil.getValue("path", propertiesKey);// 獲取文件的基本目錄 String baseName = FilenameUtils.getBaseName(fileName);// 獲取文件的基本名字(借助commons-io包讀取文件基本名稱) try { FileUtils.deleteQuietly(new File(dir + baseName + ".pdf")); FileUtils.deleteQuietly(new File(dir + baseName + ".doc")); FileUtils.deleteQuietly(new File(dir + baseName + ".docx")); } catch (Exception e) { e.printStackTrace(); } return true; } /** *刪除普通的文件(jpg,word,pdf) * @param propertiesFileName properties文件的名稱(確定讀取哪個properties文件) * @param propertiesKey properties文件中的key(確定目錄) * @param fileName 需要刪除的文件的名字(確定刪除哪個文件) * @return 刪除結果 */ public static boolean deletePlainFile(String propertiesFileName,String propertiesKey,String fileName) { if (fileName == null) { return false; } String dir = FileHandleUtil.getValue(propertiesFileName, propertiesKey);// 獲取文件的基本目錄 try { //刪除文件 // FileUtils.forceDeleteOnExit(new File(dir + fileName)); FileUtils.deleteQuietly(new File(dir + fileName)); } catch (Exception e) { e.printStackTrace(); } return true; } /****************E 刪除文件相關操作**************/ /******* S針對SptingMVC的上傳文件的處理 *************/ /** * 專門針對SpringMVC的文件上傳操作 * @param multipartFile 文件參數 * @param propertiesKey 需要讀取的path里面的key * @param fileName 文件名字,比如: ce5bd946fd43410c8a26a6fa1e9bf23c.pdf * @return 返回值是最后的文件名字,如果是word需要轉成pdf,1.doc返回值就是1.pdf */ public static String uploadSpringMVCFile(MultipartFile multipartFile,String propertiesKey,String fileName) throws Exception { String fileDir = FileHandleUtil.getValue("path", propertiesKey);// 獲取文件的基本目錄 //1.將文件保存到指定路徑 multipartFile.transferTo(new File(fileDir+fileName));//保存文件 //2.根據文件后綴判斷文件是word還是pdf,如果是word需要轉成pdf,其他的話不做處理 String fileNameSuffix = FilenameUtils.getExtension(fileName);//調用io包的工具類獲取后綴 if("doc".equals(fileNameSuffix)||"docx".equals(fileNameSuffix)){//如果后綴是doc或者docx的話轉為pdf另存一份 String fileNamePrefix = FilenameUtils.getBaseName(fileName);//獲取文件前綴名字 Word2PdfUtil.word2pdf(fileDir+fileName,fileDir+fileNamePrefix+".pdf");//進行word轉換pdf操作 fileName = fileNamePrefix+".pdf";//並將文件的名字換成新的pdf名字 } return fileName; } /******* E針對SptingMVC的上傳文件的處理 *************/ }
保存word的時候依賴於word轉pdf:
package cn.xm.jwxt.utils; import java.io.File; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.ComThread; import com.jacob.com.Dispatch; import com.jacob.com.Variant; /** * word轉pdf工具類 * @author QiaoLiQiang * @time 2018年1月5日下午7:16:12 */ public class Word2PdfUtil { static final int wdFormatPDF = 17;// PDF 格式 public static void main(String[] args) throws Exception { String source1 = "C:\\Users\\liqiang\\Desktop\\sbgl.docx"; String target1 = "C:\\Users\\liqiang\\Desktop\\sbgl.pdf"; Word2PdfUtil.word2pdf(source1, target1); } /** * 實現轉換word文檔為PDF文檔 * @param docFileName doc文件全路徑(路徑+文件名) * @param toFileName PDF文件全路徑(路徑+文件名) * @throws Exception */ public static boolean word2pdf(String docFileName,String toFileName) throws Exception { ComThread.InitSTA(); System.out.println("啟動Word..."); long start = System.currentTimeMillis(); ActiveXComponent app = null; Dispatch doc = null; try { app = new ActiveXComponent("Word.Application"); app.setProperty("Visible", new Variant(false)); Dispatch docs = app.getProperty("Documents").toDispatch(); doc = Dispatch.call(docs, "Open" , docFileName).toDispatch(); System.out.println("打開文檔..." + docFileName); System.out.println("轉換文檔到PDF..." + toFileName); File tofile = new File(toFileName); if (tofile.exists()) { tofile.delete(); } Dispatch.call(doc, "SaveAs", toFileName, wdFormatPDF); long end = System.currentTimeMillis(); System.out.println("轉換完成..用時:" + (end - start) + "ms."); } catch (Exception e) { System.out.println("========Error:文檔轉換失敗:" + e.getMessage()); return false; } finally { try { Dispatch.call(doc,"Close",false); System.out.println("關閉文檔"); if (app != null) { app.invoke("Quit", 0); } ComThread.Release(); } catch(Exception ex) { } } return true; } }