碰到一個簡單的業務, 這個文件在某個文件夾下存在,則刪除該文件,剔除多餘; 溫故下之前只是,純手寫;java
話很少少,直接上代碼;code
package com.test; import java.io.File; /** * <p class="detail"> * 功能: * 1. 比對2個文件夾,某個文件下已存在,則刪除改文件 * 2. 刪除某文件下指定匹配文件名(開頭or後綴)的文件 * </p> * * @ClassName: DelDataFile * @version V1.0 * @date 2016-12-5 */ public class DelDataFile { /** * <p class="detail"> * 功能:刪除某文件下指定匹配文件名(開頭or後綴)的文件 * startsWith 判斷字符串a 是否是以字符串b開頭. * endsWith 判斷字符串a 是否是以字符串b結尾. * </p> * @author damowang * @param path : 要刪除的文件的文件夾的路徑 * @param str : 要匹配的字符串的頭 * @return * @throws */ public static boolean delFilesByPath(String path, String str) { boolean b = false; File file = new File(path); File[] tempFile = file.listFiles(); for (int i = 0; i < tempFile.length; i++) { if (tempFile[i].getName().startsWith(str) || tempFile[i].getName().endsWith(str)) { boolean del = deleteFile(path + tempFile[i].getName()); if (del) { System.out.println("文件" + tempFile[i].getName() + "刪除成功"); b = true; } else { System.out.println("文件" + tempFile[i].getName() + "刪除失敗"); } } } return b; } /** * <p class="detail"> * 功能:刪除已存在文件 * path: 資源目錄 (40庫目錄) * exitPath : 資源目錄已存在文件 則因多餘 而 刪除 (本地目錄) * </p> * @author damowang * @param path * @param exitPath * @return * @throws */ public static boolean delFilesByExit(String path, String loaclPath) { boolean b = false; File file = new File(path); File[] tempFile = file.listFiles(); File localFile = new File(loaclPath); File[] localFiles = localFile.listFiles(); String fileName=""; String localFileName=""; // 循環源文件 for (int i = 0; i < tempFile.length; i++) { fileName = tempFile[i].getName(); //System.out.println("40庫名:"+fileName); for (int j = 0; j < localFiles.length; j++) { localFileName = localFiles[j].getName(); //System.out.println("本地資源名: "+localFileName); // 本地jar與40jar一致,則刪除 if(localFileName.equals(fileName)){ boolean del = deleteFile(loaclPath + localFileName); if (del) { System.out.println("文件" + localFileName + "刪除成功"); b = true; } else { System.out.println("文件" + localFileName + "刪除失敗"); } } } } return b; } /** * <p class="detail"> * 功能:刪除文件 * </p> * * @author damowang * @param path * @return * @throws */ private static boolean deleteFile(String path) { boolean del = false; File file = new File(path); System.out.println(path); if (file.isFile()) { file.delete(); del = true; } return del; } public static void main(String[] args) { // TODO Auto-generated method stub String path = "D:/Users/Administrator/Desktop/公共包"; String loaclPath = "F:/workSpaces/myEclipse10WorkSpace2/inNang/WebRoot/WEB-INF/lib/"; delFilesByExit(path,loaclPath); } }