Java Program to Rename a File
Program
import java.io.File;
import java.util.Scanner;
public class FileRename
{
public static void main(String[] args)
{
File src_file = null, dest_file = null;
String src_file_name = null, dest_file_name = null;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name: ");
src_file_name = sc.next();
src_file = new File(src_file_name);
System.out.print("Enter the new name: ");
dest_file_name = sc.next();
dest_file = new File(dest_file_name);
if(src_file.renameTo(dest_file))
{
System.out.println("File renamed successfully from " + src_file + " to " + dest_file);
}
else
{
System.out.println("Rename operation failed");
}
}
}
Output 1
Enter the file name: source.txt
Enter the new name: dest.txt
File renamed successfully from source.txt to dest.txt
Output 2
Enter the file name: source.txt
Enter the new name: dest.txt
Rename operation failed