Search code examples
javafile-rename

Java Rename class keeps deleting random pictures when ran


I have a linux operating system, by the way.

import java.io.*;
import java.text.DecimalFormat;
import java.awt.Desktop;

public class rename {
public static boolean renameTo(File Pictures){

    File[] listofFiles = Pictures.listFiles();
    boolean check = false;
    if(listofFiles != null){

        int count = 000;
        for(File pic : listofFiles){
            String filename = pic.getName();
            String extention = filename.substring(filename.lastIndexOf(".")+1, filename.length());
            String pictureExtention = "JPG";
            if(extention.equals(pictureExtention)){
                //we have picture, yay!
                count++;
                pic.renameTo(new File((new DecimalFormat("000").format(count))+".JPG"));
                check=true;
            }//end if

        }//end for

    }//end if
    return check;
}



public static void main(String[] args) throws IOException {
    String homePath = System.getProperty("user.home");
    File home = new File(homePath);
    File pictures = new File(home, "Test");
    Desktop.getDesktop().open(pictures);
    boolean x = renameTo(pictures);
    System.out.println(x);
}

}//end class

So when renaming a lot of JPG files, it will delete some from the file and I can't figure out why. Any ideas? I want it to rename the file 001.JPG to (lets say there are 25 pictures) 025.JPG. It correctly renames the ones that do not get deleted, however.


Solution

  • The File class's listFiles method can return its files in any order.

    There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.

    A file can be effectively deleted if the file before it, e.g. "005.JPG" gets renamed to "006.JPG" before "006.JPG" gets renamed.

    Sort the files by filename descending before renaming them to avoid the accidental deletion due to a collision in the filenames.

    Arrays.sort(files, Comparator.comparing(File::getName).reversed());