The renameTo() method of File class is used to rename the existing file in java. It returns true if the specified file is renamed successfully otherwise returns false.
Example:
package com.w3spoint; import java.io.File; public class RenameFileTest { public static void main(String args[]){ try { //File to rename File oldFile = new File("D:/Test files/file 3.txt"); //File for rename File neaFile = new File("D:/Test files/newTest.txt"); //Rename the specified file if(oldFile.renameTo(neaFile)){ System.out.println("File renamed successfully"); }else{ System.out.println("File not renamed successfully"); } } catch (Exception e) { e.printStackTrace(); } } } |
Output:
Stored data in temporary file.
File renamed successfully |
Please follow and like us: