Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to delete a file in Java

Ramesh Fadatare edited this page Jul 18, 2018 · 2 revisions

Overview

It is very simple to delete file from specific directory.Java File class provides delete() method can be used to delete files or empty directory/folder in java. Java file delete method returns true if file gets deleted and returns false if file doesn’t exist.

Delete File Example

  1. Create a file named "sample.txt" in directory "C://workspace'.
  2. Create File class object by passing file absolute location path.
  3. call delete() method of file object to delete "sample.txt" file from directory "C://workspace"
  4. delete() method returns true if and only if the file or directory is successfully deleted; false otherwise.
  5. Observe the directory whether file is deleted or not.
import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * This Java program demonstrates how to delete a file in Java.
 * @author javaguides.net
 */
public class DeleteFileExample {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(DeleteFileExample.class);
	
	public static void main(String[] args) {
		deleteFile();
	}
	public static void deleteFile() {
		File file = new File("C://workspace/sample.txt");
		if (file.delete()) {
			LOGGER.info(file.getName() + "created !!");
		} else {
			LOGGER.info("Delete operation failed");
		}
	}
}

Reference

https://docs.oracle.com/javase/8/docs/api/java/io/File.html

Clone this wiki locally

AltStyle によって変換されたページ (->オリジナル) /