How to rename file in java

Let’s learn how to rename file in java.

How to rename file in java

To rename a file renameTo() method of File class is used.

Here’s the syntax of renameTo() method.

public boolean renameTo(File dest)

how to rename file in java

renameto method returns true if and only if the renaming is succeeded; false otherwise.

Many aspects of the behavior of renameTo() method are inherently platform-dependent.

Parameters:

dest the new abstract pathname for the named file.

Throws:

SecurityException – If a security manager exists and its java.lang.SecurityManager.checkWrite (java.lang.String) method denies write access to either the old or new pathnames.

NullPointerException – If parameter dest is null.

Here in the below example first we have to predefine pathname as parameter in File class. Here’s the 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");
      }
   }
}


Output:

Rename successful


Also read – random number generator in java


java code to rename files in a folder

Here we are renaming files in a folder. Often it is very easy to rename two or more files in a folder.

But what if we have 100 to 200 files to rename? So let’s learn java code to rename 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")); 
         } 
      }
   }
}



java rename file extension

Now let’s learn java rename file extension. Here’s the java program.

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RenameFileExtension 
{
   public static boolean renameExtension(String strSource, String strNewExtension)
   {
      String target;
      String strCurrent = findExtension(strSource);
      if(strCurrent.equals(""))
      {
         target = strSource + "." + strNewExtension;
      }
      else 
      {
         target = strSource.replaceFirst(Pattern.quote("." + strCurrent) + "$",Matcher.quoteReplacement("." + strNewExtension));
      }
      return new File(strSource).renameTo(new File(target));
   }
   public static String findExtension(String strFile) 
   {
      String strExtension = "";
      int a = strFile.lastIndexOf('.');
      if(a > 0 &&  a < strFile.length() - 1) 
      {
         strExtension = strFile.substring(a + 1);
      }
      return strExtension;
   }
   public static void main(String[] args) throws IOException 
   {
      System.out.println(RenameFileExtension.renameExtension("A:\\java.txt", "pdf"));
   }
}


Output:

true


move file

In java we can move file using Files.Path move() method. This method renames or moves file permanently.

Syntax:

public static Path move(Path source, Path target, CopyOption… options) throws IOException


Parameters:

source – the path to the file to move.

target – the path to the target file (may be associated with a different provider to the source path).

options – options specifying how the move should be done.

Returns:

the path to the target file.

Throws:

UnsupportedOperationException
FileAlreadyExistsException
DirectoryNotEmptyException
IOException
SecurityException

Now let’s see an example on java move file.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaMoveFile
{
   public static void main(String[] args) throws IOException
   {
      Path move = Files.move(Paths.get("B:\flowerbrackets.txt"), Paths.get("B:\Softs\flowerbrackets.txt"));
      if(move != null)
      {
         System.out.println("File moved successfully");
      }
      else
      {
         System.out.println("Failed to move the file");
      }
   }
}


Output:

File moved successfully.

So this is all about how to rename file. I hope you guys have understood the concept of renaming file in java.