File Rename Example
This program demonstrates renaming a file.
Problem Statement
Write a Java program that renames a file if it exists.
Source Code
| 1 | import java.io.*; |
| 2 | public class FileRenameExample { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq File Rename Example"); |
| 5 | File oldFile=new File("old.txt"); |
| 6 | File newFile=new File("new.txt"); |
| 7 | if(oldFile.exists()){ |
| 8 | if(oldFile.renameTo(newFile)){ |
| 9 | System.out.println("Eduinq File Renamed Successfully"); |
| 10 | } else { |
| 11 | System.out.println("Eduinq Exception: Rename Failed"); |
| 12 | } |
| 13 | } else { |
| 14 | System.out.println("Eduinq Exception: File Not Found"); |
| 15 | } |
| 16 | } |
| 17 | } |
Program Output
Eduinq File Rename Example Eduinq Exception: File Not Found
Explanation
Renaming uses File.renameTo() method. - Checks existence before renaming to avoid errors. - Provides feedback for success/failure. - In enterprise systems, renaming is used for version control and file organization. Conclusion: Shows renaming a file safely.