Rename a File in Java

To rename file name, we use renameTo() method in file. Call renameTo() method on old file handle and pass new file handle to the method as parameter. Using renameTo() method we can also move file from one directory to the other desired directory by changing File Path.

Rename a File

package com.jminded.java.io;

import java.io.File;

/**
 * https://jminded.com
 * @author Umashankar
 *
 */
public class RenameFiles {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// file handle for old file
		File oldFileHandle = new File("oldFile.txt");
		// file handle for new file
		File newFileHandle = new File("newFile.txt");

		// rename oldFile.txt to newFile.txt call renameTo() on old file handle
		if (oldFileHandle.renameTo(newFileHandle)) {
			// rename success
			System.out.println("Rename successful!");
		} else {
			System.out.println("Rename failed!");
		}
	}

}

References

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

Leave a Comment