- 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
Java Program to rename a file or directory
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
Note − The output may vary on Online Compilers.
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(); }
Advertisements