beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to rename file in Java – renameTo() method

By Chaitanya Singh | Filed Under: Java I/O

Earlier we saw how to create, read, write, append to a file in java. In this tutorial we will see how to rename a file in java using renameTo() method.

public boolean renameTo(File dest)

It returns true if the file is renamed successfully else it returns false. It throws NullPointerException – If parameter dest is null.

Complete Example:

import java.io.File;
public class RenameFileJavaDemo
{
    public static void main(String[] args)
    {	
        //Old File
	File oldfile =new File("C:\\myfile.txt");
	//New File
	File newfile =new File("C:\\mynewfile.txt");
	/*renameTo() return boolean value
	 * It return true if rename operation is
	 * successful
	 */
        boolean flag = oldfile.renameTo(newfile);
	if(flag){
	   System.out.println("File renamed successfully");
	}else{
	   System.out.println("Rename operation failed");
	 }
    }
}

Output:

File renamed successfully

Reference:
renameTo() – Javadoc

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap