ADVERTISEMENT
ADVERTISEMENT

Java program to rename an existing file

In this Java program, we are going to learn how to rename an existing file? This task can we performed using 'renameTo()' method, which is a method of 'File' class.

Given a file and we have to rename the file name.

To rename a file name, we use renameTo() method, which is a method of File class. Here, we are using statement File F=new File("f:/Includehelp.txt"); to create an object of File class by passing file name. Here, "Includehelp.txt" is the file name, which is saved in "f:" drive.

Consider the program:

import java.io.File;
import java.io.IOException;

public class RenameFile {
  public static void main(String[] args) {
    try
    // Here F is the object of the Existing file named 
    // with Includehelp which is to be renamed
    {
      File F = new File("f:/Includehelp.txt");

      // Here T is the object of the renamed file 
      // of Includehelp which is Include.txt
      File T = new File("f:/Include.txt");

      // Rename the file Includehelp.txt 
      // into Include.txt
      F.renameTo(T);

      // Print the result if file renamed
      System.out.println("File Rename Successfully...");
    }
    // If any error occurs while renaming the file
    catch (Exception e) {
      System.out.println(e);
    }
  }
}

Output

File Rename Successfully...

Java File Handling Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.