StackTips

How to delete and rename a file in java

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

Nilanchala Panigrahy

A blogger, a bit of tech freak and a software developer. He is a thought leader in the fusion of design and mobile technologies. He is the author of Xamarin Mobile Application Development for Android Book (goo.gl/qUZ0XV3)