StackTips

How to delete and rename a file in java

nilan avtar

Written by:

Nilanchala,  2 min read,  updated on September 17, 2023

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();
		}
	}
}

Java Collection APIs

The Collections framework in Java defines numerous different data structures in which you can store, group, and retrieve objects.

>> CHECK OUT THE COURSE

Keep exploring

Let’s be friends!