Java rename file in directory code example

Example 1: How to rename file in java

// rename file in java example
import java.io.*;
public class RenameFile
{
   public static void main(String[] args) throws IOException
   {
      File oldFile = new File("D:\\Project\\flower.txt");
      File newFile = new File("D:\\Project\\flowerbrackets.txt");
      if(oldFile.renameTo(newFile))
      {
         System.out.println("Rename successful");
      }
      else
      {
         System.out.println("Rename failed");
      }
   }
}

Example 2: java code to rename all files in a folder

// java code to rename all files in a folder
import java.io.File;
public class RenameAllFilesDemo 
{
   public static void main(String[] args) 
   {
      // folder path 
      String strPath = "D:\\Users\\sachin\\java\\sachinfolder";
      // let's create new folder
      File newfolder = new File(strPath);
      File[] arrFile = newfolder.listFiles();
      for(int a = 0; a < arrFile.length; a++) 
      {
         if(arrFile[a].isFile()) 
         {
            File file = new File(strPath + "\\" + arrFile[a].getName()); 
            String strFileName = arrFile[a].getName(); 
            String[] tokens = strFileName.split("\s"); 
            String strNewFile = tokens[1]; 
            System.out.println(strFileName); 
            System.out.print(strNewFile);
            file.renameTo(new File(strPath + "\" + strNewFile + ".pdf")); 
         } 
      }
   }
}

Tags:

Java Example