Tutorials Java How to delete and rename a file in java

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();
		}
	}
}
Total
0
Shares
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Shivam Singh
Shivam Singh
7 years ago

Nice post and also visit simple code for delete a file in java Delete file in java

Previous Post
Java Tutorials

Copy file from one folder to another in java

Next Post
Java Tutorials

Count line word and characters in file

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
1
0
Would love your thoughts, please comment.x
()
x