Java | Renaming a file
In Java we can rename a file using renameTo(newName) method that belongs to the File class.
Declaration:
Following is the declaration for java.io.File.renameTo(File dest) method:
public boolean renameTo(File dest)
Parameters:
dest – The new abstract pathname for the existing abstract pathname.
Exception:
SecurityException : If a security manager exists and its method denies write access to either the old or new pathnames.
NullPointerException : If parameter destination is null.
// Java program to rename a file. import java.io.File; public class GeeksforGeeks { public static void main(String[] args) { File oldName = new File("C:\Users\Siddharth\Desktop\java.txt"); File newName = new File("C:\Users\Siddharth\Desktop\GeeksforGeeks.txt"); if (oldName.renameTo(newName)) System.out.println("Renamed successfully"); else System.out.println("Error"); } } |
Renamed successfully
Recommended Posts:
- File Permissions in Java
- Delete a file using Java
- Java Class File
- Java.io.File Class in Java
- Check if a File is hidden in Java
- How to play an Audio file using Java
- Moving a file from one directory to another using Java
- Java | Appending String to a File
- How to run java class file which is in different directory?
- Copying file using FileStreams in Java
- Reading a CSV file in Java using OpenCV
- Writing a CSV file in Java using OpenCSV
- Size of file on the Internet using Java
- Myth about the file name and class name in Java
- File getCanonicalPath() method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




