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:

ALGORITHM:

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.

JAVA CODE:

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

import java.io.IOException;
import java.io.File;
import java.util.Scanner;
public class RenameTextFile
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
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.

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

If any error occurs print an exception.

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

OUTPUT:

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

 

Download Complete Code

Comments

No comments yet