先使用 FileFilter 來篩選我要的檔案來做搬檔的動作
篩選條件為
檔名開頭為「TEST」fileName.startsWith("TEST")
檔名結尾為「.txt」 fileName.endsWith(".txt")
搬檔過程中
先判斷
要搬的東西是否為檔案 fileNames[i].isFile()
並且新路徑中並沒有同樣檔名的檔案 !newFile.exists()
若是的話 就直接搬過去 FileUtils.moveFileToDirectory(fileNames[i], newFilePath, true);
若不是的話 先將舊檔改檔名以後再搬過去
我的測試方式
先在C槽建立 FileTest資料夾,並且再在裡面建立一個Old的資料夾,
執行第一次
為了測試檔案重複的情況,所以到New資料夾下將所有檔案複製到Old資料夾下,然後再執行一次
test.java
import java.io.File;
import java.io.FileFilter;
import org.apache.commons.io.FileUtils;
class test {
public static void main(String[] args) {
System.out.println("main");
moveToPath();
}
// 搬檔
private static void moveToPath() {
File oldPath = new File("C:\\FileTest\\Old\\");
File[] fileNames;
// 將資料夾下檔案依照「TEST*.txt」條件轉成陣列並存入fileNames
fileNames = oldPath.listFiles(new FileFilter() {
@Override
public boolean accept(File pathName) {
String fileName = pathName.getName();
if (fileName.startsWith("TEST") && fileName.endsWith(".txt")) {
System.out.println(fileName + "我沒有被排除唷");
return true;
} else {
System.out.println(fileName + "我被排除了");
return false; // 排除
}
}
});
try {
// 新路徑
String newPath = "C:\\FileTest\\New\\";
// 依照上面抓到的檔案陣列跑回圈去做處理
for (int i = 0; i < fileNames.length; i++) {
File newFilePath = new File(newPath);
//newFile是用來判斷 檔名重複的
File newFile = new File(newPath + fileNames[i].getName());
// 若fileNames[i]是檔案並且新路徑沒有同名字的檔案時,就搬移至新路徑
if (fileNames[i].isFile() && !newFile.exists()) {
System.out.println("檔案要被搬過去了");
//False不建立資料夾 true會建立資料夾
FileUtils.moveFileToDirectory(fileNames[i], newFilePath, true);
//新路徑會有檔名重複的情況
}else if(fileNames[i].isFile() && newFile.exists()){
System.out.println("檔名會重複啦");
//建一個新名字的String
String newName = fileNames[i].getName().replace(".", "(2).");
System.out.println("newName="+newName);
File newNameFile = new File(fileNames[i].getParent() + "\\" + newName);
//將舊檔案先重新命名
fileNames[i].renameTo(newNameFile);
//將檔案搬過去
FileUtils.moveFileToDirectory(newNameFile, newFilePath, true);
}
}
} catch (Exception e) {
System.out.println("我壞了");
}
}
}
