Search code examples
javafile-rename

Java File.renamTo not working


I have made the code which renames all the jpg files in a directory from 1 to n (number of files).. if there were let say 50 jpg files that after running the program all the files are renamed to 1.jpg ,2.jpg and so on till 50.jpg But i am facing the problem if I manually rename the file let say 50.jpg to aaa.jpg then again running the program doesn't rename that file I have wasted one day to resove that issue Kindly help me Code:

public class Renaming {
    private static String path;             // string for storing the path
    public static void main(String[] args) {

        FileReader fileReader = null;           // filereader for opening the file
    BufferedReader bufferedReader = null;   // buffered reader for buffering the data of file
        try{
            fileReader = new FileReader("input.txt");   // making the filereader object and paasing the file name
            bufferedReader = new BufferedReader(fileReader); //making the buffered Reader object
            path=bufferedReader.readLine();
            fileReader.close();
            bufferedReader.close();
        }
        catch (FileNotFoundException e) {           // Exception when file is not found
            e.printStackTrace();
        } 
        catch (IOException e) {                     // IOException
            e.printStackTrace();
        }
        finally {

             File directory=new File(path);

        File[] files= directory.listFiles();        // Storing the all the files in Array

        int file_counter=1;
           for(int file_no=0;file_no<files.length;file_no++){
               String Extension=getFileExtension(files[file_no]);   //getting the filw extension
               if (files[file_no].isFile() && (Extension .equals("jpg")|| Extension.equals("JPG"))){            // checking that if file is of jpg type then apply renaming         // checking thaat if it is file

                File new_file = new File(path+"\\"+files[file_no].getName()); //making the new file

                new_file.renameTo(new File(path+"\\"+String.valueOf(file_no+1)+".jpg"));   //Renaming the file
               System.out.println(new_file.toString());
                file_counter++;             // incrementing the file counter
            }

        }

        }


}

private static String getFileExtension(File file) {     //utility function for getting the file extension 
    String name = file.getName();
    try {
        return name.substring(name.lastIndexOf(".") + 1);   // gettingf the extension name after . 
    } catch (Exception e) {
        return "";
    }
}`

Solution

  • first of all, you should use the path separator / . It's work on Windows, Linux and Mac OS. This is my version of your problem to rename all files into a folder provide. Hope this will help you. I use last JDK version to speed up and reduce the code.

    public class App {
    
        private String path = null;
        public static int index = 1;
    
        public App(String path){
            if (Files.isDirectory(Paths.get( path ))) {
                this.path = path;
            }
        }
    
        public void rename() throws IOException{
            if ( this.path != null){
                Files.list(Paths.get( this.path ))
                .forEach( f -> 
                {
                    String fileName = f.getFileName().toString();
                    String extension = fileName.replaceAll("^.*\\.([^.]+)$", "$1");             
    
                    try {
                        Files.move( f ,Paths.get( this.path + "/" +   App.index + "." + extension));
                        App.index++;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }           
                );
            }
        }
    
        public static void main(String[] args) throws IOException {
            App app = new App("c:/Temp/");
            app.rename();
        }
    }