- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Rename file or directory in Java
The method java.io.File.renameTo() is used to rename a file or directory. This method requires a single parameter i.e. the name that the file or directory is renamed to and it returns true on the success of the renaming or false otherwise.
A program that demonstrates this is given as follows −
Example
import java.io.File; public class Demo { public static void main(String[] args) { try { File file1 = new File("demo1.txt"); File file2 = new File("demo2.txt"); file1.createNewFile(); file2.createNewFile(); boolean flag = file1.renameTo(file2); System.out.print("File renamed? " + flag); } catch(Exception e) { e.printStackTrace(); } } }
The output of the above program is as follows −
Output
File renamed? true
Now let us understand the above program.
The method java.io.File.renameTo() is used to rename the file. Then the boolean value returned by the method is printed. A code snippet that demonstrates this is given as follows −
try { File file1 = new File("demo1.txt"); File file2 = new File("demo2.txt"); file1.createNewFile(); file2.createNewFile(); boolean flag = file1.renameTo(file2); System.out.print("File renamed? " + flag); } catch(Exception e) { e.printStackTrace(); }
- Related Articles
- Java Program to rename a file or directory
- Delete the file or directory in Java
- Check for file or directory in Java
- Determine if file or directory exists in Java
- Delete file or directory on termination in Java
- Mark file or directory Read Only in Java
- Java Program to delete file or directory
- Determine if File or Directory is hidden in Java
- Get the absolute path for the directory or file in Java
- Specify a path for a file or a directory in Java
- Java Program to get name of specified file or directory
- Java Program to get the name of the parent directory of the file or directory
- Java Program to check if a file or directory is readable
- How to rename directory using Python?
- Create temporary file in specified directory in Java

Advertisements