Rename File Java

Rename File Java

In this sample java class you will see how to rename existing java file. To rename existing you will have to create File instance with old file and rename it as shown below:

package com.javahonk;

import java.io.File;

public class RenameFile {

	public static void main(String[] args) {
		
		File oldFile = new File("C:\\JavaHonk\\File\\JavaHonk.txt");
		File newName = new File("C:\\JavaHonk\\File\\JavaHonk_Renamed.txt");
		
		if (newName.exists()) {
			System.out.println("File name already exists");
		} else {
			boolean success = oldFile.renameTo(newName);
			if (success) {
				System.out.println("File renamed successfully");
			}
		}		

	}

}

 

Output:

Rename File Java

For more information on File please refer oracle documentation here

Leave a Reply

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