StackTips

How to delete and rename a file in java

nilan avtar

Written by

Nilanchala,  2 min read,  2.92K views, updated on Sept. 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();
		}
	}
}

Beginner's Guide to Java Collections

This course covers the fundamentals of java collections framework covering different data structures in Java to store, group, and retrieve objects.

>> CHECK OUT THE COURSE
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.

Related posts

Let’s be friends!

🙌 Stay connected with us on social media for the latest updates, exclusive content, and more. Follow us now and be part of the conversation!