How to delete a file in Java - RameshMF/java-io-guide GitHub Wiki
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
- Create a file named "sample.txt" in directory "C://workspace'.
- Create File class object by passing file absolute location path.
- call delete() method of file object to delete "sample.txt" file from directory "C://workspace"
- delete() method returns true if and only if the file or directory is successfully deleted; false otherwise.
- 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");
}
}
}