Write a java program to Rename an existing file


The code renames an existing file named "file.txt" to a new file named "Newfile.txt".

The File class is used to create objects for the existing file and the renamed file. The renameTo() method of the File class is then used to rename the file. The method returns a boolean value indicating whether the rename operation was successful or not.

If the file is renamed successfully, the program will output the message "File Rename Successfully...". If an exception is thrown during the rename operation, the program will catch the exception and output its message.

Source Code

import java.io.File;
import java.io.IOException;
public class File_Rename
{
	public static void main(String[] args)
	{
		try
		{
			File old_file = new File("file.txt"); // Existing file named 
			File new_file = new File("Newfile.txt"); //object of the renamed file			
			old_file.renameTo(new_file); // Rename the file
			System.out.println("File Rename Successfully...");
		}
		catch (Exception e)
		{
			System.out.println(e);
		}
	}
}

Output

File Rename Successfully...