StackTips
 2 minutes

How to delete and rename a file in java

By Nilanchala @nilan, On Sep 17, 2023 Java 2.42K Views

This post provides sample program explaining how to delete and rename a file in java

Rename file in Java

package com.javatechig;

import java.io.File;
import java.io.IOException;

public class RenameFile {

	public static void main(String[] args) {

		/* File (or directory) with old name */
		File file = new File("/Users/Neel/Documents/Workspace/file.txt");

		/* File (or directory) with new name */
		File file2 = new File("/Users/Neel/Documents/Workspace/new-file.txt");

		if (file2.exists()) {
			try {
				throw new java.io.IOException("File already exists!");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		/* Rename file */
		boolean success = file.renameTo(file2);
		if (!success) {
			System.out.println("Couldn't rename file!");
		} else {
			System.out.println("File renamed successfully!");
		}
	}

}

Delete file in Java

package com.javatechig;

import java.io.File;

public class DeleteFile {

	public static void main(String[] args) {
		try {
			File file = new File(
					"/Users/Neel/Documents/Workspace/file1.txt");

			if (file.delete()) {
				System.out.println(file.getName() + " is deleted!");
			} else {
				System.out.println("Delete operation is failed.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
nilan avtar

Nilanchala

I'm a blogger, educator and a full stack developer. Mainly focused on Java, Spring and Micro-service architecture. I love to learn, code, make and break things.