[英]Java: Rename Files - Not renaming files correctly
以下Java代碼重命名文件,但未重命名我想要的文件。 我希望重命名文件按照“部分”的編號從目錄的開頭開始到結尾(而不是它在特定目錄中添加的時間)開始,但是不這樣做。 我是否可以放入“ if”支票,例如: if filename.contains(j)
然后進行處理?
import java.io.File;
public class RenameFile2 {
public static void main(String[] args) {
String absolutePath1 = "1 to 4";
String absolutePath2 = "6 to 9";
String absolutePath3 = "10 to 99";
String absolutePath4 = "100 to 224";
File dir1 = new File(absolutePath1);
File dir2 = new File(absolutePath2);
File dir3 = new File(absolutePath3);
File dir4 = new File(absolutePath4);
File[] filesInDir1 = dir1.listFiles();
File[] filesInDir2 = dir2.listFiles();
File[] filesInDir3 = dir3.listFiles();
File[] filesInDir4 = dir4.listFiles();
int i1 = 1;
for(File file:filesInDir1) {
String name = file.getName();
String newName = "550 00510 00" + i1 + ".pdf";
String newPath = absolutePath1 + "\\" + newName;
file.renameTo(new File(newPath));
System.out.println(name + " changed to " + newName);
i1++;
}
int i2 = 6;
for(File file:filesInDir2) {
String name = file.getName();
String newName = "550 00510 00" + i2 + ".pdf";
String newPath = absolutePath2 + "\\" + newName;
file.renameTo(new File(newPath));
System.out.println(name + " changed to " + newName);
i2++;
}
int i3 = 10;
for(File file:filesInDir3) {
String name = file.getName();
String newName = "550 00510 0" + i3 + ".pdf";
String newPath = absolutePath3 + "\\" + newName;
file.renameTo(new File(newPath));
System.out.println(name + " changed to " + newName);
i3++;
}
int i4 = 100;
//int j = 99;
for(File file:filesInDir4) {
String name = file.getName();
/* if(name.contains(j))
{
}
*/
String newName = "550 00510 " + i4 + ".pdf";
String newPath = absolutePath4 + "\\" + newName;
file.renameTo(new File(newPath));
System.out.println(name + " changed to " + newName);
i4++;
}
}
}
列出文件后,您需要對文件進行排序, listFiles()
不能保證任何順序。
File[] filesInDir1 = dir1.listFiles();
Arrays.sort(filesInDir1);
您可能需要實現一個Comparator
並調用Arrays.sort(filesList, comparator)
才能對它們進行自定義排序。
一旦文件具有排序順序,就可以根據需要應用重命名邏輯。
另一個改進是,如果您只想列出帶有模式的文件,則可以在列出時進行過濾。
final String pattern = "regexpattern";
dir1.listFiles(new FilenameFilter(){
public boolean accept( File dir, String name ) {
return name.matches( pattern );
}
});
在.listFiles()
的文檔中 ,它說:
不能保證結果數組中的名稱字符串會以任何特定順序出現; 尤其不能保證它們按字母順序出現。
您需要按照要按特定順序處理數組的順序對數組進行排序。
其他注意事項和建議:
String.contains()
將String
用作參數,而不是int
。 您已在問題中注釋了此代碼。 File newPath = new File(dir1, newName);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.