How To Rename A File In Java

This little program demonstrate how to rename a file in Java. The code

  • Takes original file name and renamed file name as parameter
  • Checks whether the file exists
  • Checks whether the input file provided is a directory
  • Renames a file if it exists and is not a directory
  • Throws an error if problem occurs renaming the file.

package com.kushal.utils;

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On 05-04-2009
 *
 * Demonstrate the process of renaming a file in Java
 */

import java.io.File;

public class FileRenameInJava {

	public static void renameFile(String originalFileName,
			String renamedFileName) {

		File originalFile = new File(originalFileName);
		/**
		 * Check if file exists
		 */
		boolean fileExists = originalFile.exists();

		/**
		 * Check if it is a directory
		 */
		boolean isDirectory = originalFile.isDirectory();

		/**
		 * If file does not exist, return
		 */
		if (!fileExists) {

			System.out.println("File does not exist: " + originalFileName);
			System.out.println("Rename Operation Aborted.");
			return;
		}
		/**
		 * If file is a directory, return
		 */
		if (isDirectory) {
			System.out
					.println("The parameter you have provided is a directory: "
							+ originalFileName);
			System.out.println("Rename Operation Aborted.");
			return;
		}

		File renamedFile = new File(renamedFileName);

		boolean renamed = originalFile.renameTo(renamedFile);
		if (renamed) {
			System.out.println("File Has Been Renamed Successfully.");
			System.out.println("Original File Name: " + originalFileName);
			System.out.println("Rename File Name: " + renamedFileName);
		} else {
			System.out
					.println("Error occurred while trying to rename the file.");
		}

	}

	public static void main(String[] args) {
		renameFile("C:/Temp/def.txt", "C:/Temp/abc.txt");
	}
}

———————-
Here is the sample output:

File Has Been Renamed Successfully.
Original File Name: C:/Temp/def.txt
Rename File Name: C:/Temp/abc.txt