Coders Packet

Java Program to Rename a Text File

By Adinath Kishor Joshi

Hello Learners, in this article, we will learn about how to rename a text file using Java."File" package is an inbuilt package of Java that is used for carrying out this program.

Let us look at the algorithm and code:


1. Start.

2. In the try block create an object of the existing file and the renamed file.

3. Use these objects to rename the file.

4. Print "File renamed successfully" if the file is successfully renamed.

5. In the catch block print if any exception occurs.


Firstly, import important packages and take input to rename your file.

import java.util.Scanner;
public class RenameTextFile
public static void main (String[]args)
Scanner sc = new Scanner (;
System.out.println ("Enter name to rename your file");
String r = sc.nextLine ();

Create an object of the existing file and the renamed file and use these objects to rename the file.

File E = new File ("C:/java/file.txt");
File R = new File (r + ".txt");
System.out.println ("Your File is renamed");

If any error occurs print an exception.

catch (Exception e)
System.out.println (e);


C:\java>java RenameTextFile
Enter name to rename your file
Your File is renamed


Download Complete Code


No comments yet