Tutorialspoint examples

Learn java tutorial with examples for beginners online

rename file in java program


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.tutorialspointexamples;
 
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

Download this example.

Download tutorialspointexamples Android App
Copyright © 2018 Tutorialspoint examples DMCA.com Protection Status