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
  • 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

Enjoyed this post? Try these related posts

  1. How to write to file in Java using BufferedWriter
  2. How to read file in Java using BufferedReader
  3. Java – Find files with given extension
  4. How to Copy a File to another File in Java
  5. How to check if a File is hidden in Java
  6. Append to a file in java using BufferedWriter, PrintWriter, FileWriter

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 – 2021 BeginnersBook . Privacy Policy . Sitemap