Rename File in Java – File.renameTo()

Problem Statement:

How to Rename File in Java?

Java IO Package

Java IO Package

Description

Rename file in java is very simple using Java IO API. We have to use renameTo() of File class passing the new instance of file as shown below. Note this method is inherently platform dependent. This method returns true if rename operation is successful and returns false if the rename operation fails. If the new file with the destination abstract pathname already exists or the file doesn’t exist, the renameTo() methods fails..

Always the return value should be checked to make sure the rename was successful.

Code

package com.stixs.java.io;
 
import java.io.File;
 
public class STXRenameFile 
{
    public static void main(String[] args)
    { 
         File currentFile =new File("technostixs.txt");
         File newFile =new File("technostixsNew.txt");
 
         // Renames the file denoted by the abstract pathname provided. 
         // Behavior of this method are inherently platform-dependent
         if(currentFile.renameTo(newFile)){
              System.out.println("STXRenameFile: technostix.txt renamed succesfully to technostixsNew.txt!!");
         }else{
              System.out.println("STXRenameFile: Renaming to technostixsNew.txt failed!!");
         }
     }
}

Output

Case 1: There should be a fail named technostixs.txt at c:\\technostixs\\java path.

STXRenameFile: technostix.txt renamed successfully to technostixsNew.txt!!

Case 2 : If the file technostixs.txt doesnot exist, the renameTo() methods fails.

STXRenameFile: Renaming to technostixsNew.txt failed!!

Java API used in the example

renameTo

Reference

Refer below path to get the complete details about Java IO File class.

http://docs.oracle.com/javase/8/docs/api/java/io/File.html

——————————————————————————–

You may also like this

——————————————————————————–

About TechnoStixs.com

TechnoStixs

TechnoStixs.com is a dedicated weblog for Java/J2EE and web developers. We take pride in our work. Every publication is carefully analyzed, written and tested to ease the understanding of the topic or subject.

We cover Java Core Technologies, eCommerce, J2EE Frameworks, Web Service, Build Tools, Unit Test Frameworks and Others.


1,504 total views, 1 views today

Add comment