best way in java to rename a file , there are about 500 files in a directory

Suresh S picture Suresh S · Apr 27, 2010 · Viewed 73.3k times · Source

I have 500 pdf files in a directory. I want to remove first five characters of a filename and rename it.

Answer

gmhk picture gmhk · Apr 28, 2010

Sample code for you to rename the List of files in a given directory. In the below example, c:\Projects\sample is the folder, the files which are listed under that have been renamed to 0.txt, 1.txt, 2.txt, etc.

I hope this will solve your problem

import java.io.File;
import java.io.IOException;

public class FileOps {


    public static void main(String[] argv) throws IOException {

        File folder = new File("\\Projects\\sample");
        File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {

            if (listOfFiles[i].isFile()) {

                File f = new File("c:\\Projects\\sample\\"+listOfFiles[i].getName()); 

                f.renameTo(new File("c:\\Projects\\sample\\"+i+".txt"));
            }
        }

        System.out.println("conversion is done");
    }
}