Java File Rename Sample Code

The Java File class comes with a method called renameTo() that will attempt to rename a file within the filesystem. Keep in mind there are some platform specific dependencies when trying to rename a file. If the destination filename already exists, the call will fail and return false, which is why it’s important to check the return and not just assume it worked. The destination filename cannot be NULL or a NullPointerException will be thrown.

Java Class: File
Method Name: renameTo()
Parameters: java.io.File destination
Return Type: boolean
Exceptions: SecurityException, NullPointerException

Java File Rename Sample Code

package com.jcd.java.tutorials;

import java.io.File;

public class JavaRenameFile {


	 public static void main( String[] args )
	 {
		//String with path of filename 
		String sampleFile = "C:\\Users\\Admin\\Documents\\JavaFile.txt";
		String sampleFileRename = "C:\\Users\\Admin\\Documents\\JavaFileBAK.txt";
		
		//Create File objects old filename
		File oldFile = new File(sampleFile);
		
		//Get just the name of old file without path
		String justOldName = oldFile.getName();
		
		//Create File object for new filename
		File newFile = new File(sampleFileRename);
		
		//Get just the name of new file without path
		String justNewName = newFile.getName();
		
		try 
		{
			//Attempt to rename the file
			if(oldFile.renameTo(newFile))
			{
				System.out.println("Successfully Renamed "+justOldName+" To "+justNewName);
			}
			else
			{
				System.out.println("Unsuccessfully Renamed "+justOldName+" To "+justNewName);
			}
		}
		catch(Exception ex)
		{
			System.out.println("Exception:"+ex.toString());
		}
		
	 }
}


Java File Exist Sample Output (SUCCESS)

Successfully Renamed JavaFile.txt To JavaFileBAK.txt


Java File Rename Sample Output (FAILED)

Unsuccessfully Renamed JavaFile.txt To JavaFileBAK.txt


A few key points to keep in mind when using the File.renameTo() class method:

  1. If source and destination file names are the same, there is no change.
  2. If the file to rename is a symbolic or soft link, then only the symbolic link itself is moved.
  3. The renameTo() method may be used to rename a directory but the directory must be empty.



Java References:

Add a Comment

Your email address will not be published. Required fields are marked *