How to Rename a File Using Java

Java


In this article, we show how to rename a file with Java.

With Java, we can rename a file in any directory on your computer.

In Java, a file can be renamed with the renameTo() function.

The code to rename a file in Java is shown below.



So in the file above we create a class called Renamefile.

We then put in our main() method.

In the main method, we create a file object, f, and pass the parameter named "oldname.txt" into the this File object.

So at this point in the code, the File object f has the value of oldname.txt.

We then call the renameTo() function through the if statement.

The function is f.renameTo(newFile("newname.txt"). This renames the file from oldname.txt to newname.txt.

Since we didn't specify the path in the file names, the Java program looks in the current directory, the one storing this Java file, to look for the file name oldname.txt.

If you want to specify a directory other than the current directory, then you will have to specify the complete path to the file.

Since this differs according to what operating system you are using, this is the only part of Java that becomes platform dependent.

In a Windows computer, you normally specify the drive you are using with a letter such as the C drive and then specify the path from there to the file that you want to rename.

So if you have a file you want to rename that in the C:\Users\ directory, then you would write this into the string as "C:\\Users\\"

This is because "\" is an escape character; it's used for escaping strings. To show "\" in a string, you would have to put double forward slashes "\\".



And this is all that is required to rename files either in the current directory (where you are saving this Java file to) or to any directory.


Related Resources

How to Check if a File Exists Using Java

How to Check if an Object is a File Using Java

How to Check if a File is a Directory Using Java

How to Create a New File Using Java

How to Delete a File Using Java

How to Create a New Directory Using Java

How to List All Files in a Directory Using Java

How to Read a File Using Java

How to Write Data to a File Using Java

How to Get the Size of a File Using Java




HTML Comment Box is loading comments...