Search code examples
javafilestringbuffersubstring

Removing Parts of File names in Folder


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));
}

Solution

  • 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.