Java IOjava-io-examples

How to rename a file

Posted On
Posted By admin

In this blog post ,I will be showing you how you can rename a file. Consider the following code snippet:


package learnjava.io;

import java.io.File;

public class RenameFileDemo {
public static void main(String args[]){
String fileName = "C:/Test.txt";
String newFileName = "C:/test2.txt";
File file = new File(fileName);
if(file.exists()){
File newFile = new File(newFileName);
boolean renamed = file.renameTo(newFile);
if(renamed)
System.out.println("File renamed successfully");
else
System.out.println("There was an error in renaming the file");
}
else
System.out.println("File is missing");
}
}

If you run this code, it will produce the following output:

File renamed successfully

 

There is a method called File.renameTo which can be used to rename a file. It accepts as argument a file object. The file object should be constructed with the new name to be given to the file. Note that the full path needs to be specified.

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment