Removing Parts of File names in Folder

大兔子大兔子 提交于 2019-12-24 09:29:02

问题


The code below works, but my problem is that the console output shows correctly for example:

3-M-ALABAMA-SUIQUARTER2
3-M-ALABAMA-SUIQUARTER2
3-M-ALABAMAW-22017
3-M-ALABAMAW-22017

The output above show that my index is -2017 however when the actual file name is being change in the folder some of the File Names are skipped. For example

Orginal file name: 3-M-ALABAMA-SUIQUARTER2-2017200346-CD6140
Console Output: 3-M-ALABAMA-SUIQUARTER2
Some of Files in folder unchanged: 3-M-ALABAMA-SUIQUARTER2-2017200346-CD6140

However some of the files in the folder have 3-M-BATTLECREEKMIW-22017-2017200346-CD619B and some are 3-M-ARLINGTONOHLOCALW-2-2017200346-CD61A8

So I think java is confused as to where to cut off when the actual change is being made in file alteration? can you help me?

for(File file:filesInDir) {
       x++;
       String name = file.getName().substring(0, file.getName().indexOf("-2017"));
       String newName = name;
       System.out.println(newName); // prints prints to file 
       String newPath = absolutePathOne + "\\" + newName;
       file.renameTo(new File(newPath));
}

回答1:


Okay there any other way to rename the files?

Yes. Use the newer NIO 2 classes, in particular the Files.move() method.

At the very least, replace file.renameTo(new File(newPath)) with:

Files.move(file.toPath(), Paths.get(newPath));

That will throw descriptive exception if move fails, instead of the false boolean return value from renameTo().

You should also change the rest of the code to use the newer classes. Although not required, it is recommended to do so.



来源:https://stackoverflow.com/questions/45174365/removing-parts-of-file-names-in-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!