In this quick tutorial, we will learn how to delete a file in Java.
We will see two ways to delete a file in Java:
- Delete the file using the delete() method of the java.io.File class
- Delete the file using Files.delete(Path) method of Java NIO
1. Delete the File using File.delete() Method
- Create a file named "sample.txt" in the directory "C://workspace'.
- Create a File class object and pass the file's absolute location path.
- call the delete() method of the file object to delete the "sample.txt" file from the directory "C://workspace"
- delete() method returns true if and only if the file or directory is successfully deleted; false otherwise.
- Observe the directory whether the 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");
}
}
}
2. Delete File using Java NIO’s Files.delete()
It is recommended to use Java NIO’s Files.delete() method to delete the file in Java:
import java.io.IOException;
import java.nio.file.*;
public class DeleteFileExample {
public static void main(String[] args) throws IOException {
// File or Directory to be deleted
Path path = Paths.get("./demo.txt");
try {
// Delete file or directory
Files.delete(path);
System.out.println("File or directory deleted successfully");
} catch (NoSuchFileException ex) {
System.out.printf("No such file or directory: %s\n", path);
} catch (DirectoryNotEmptyException ex) {
System.out.printf("Directory %s is not empty\n", path);
} catch (IOException ex) {
System.out.println(ex);
}
}
}
Reference
- https://docs.oracle.com/javase/10/docs/api/java/io/File.html
- https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/file/Files.html
File Handling Examples
- How to Create a New File in Java
- How to Write to File in Java
- How to delete a file in Java
- How to Copy the File in Java
- How to Move a File in Java
- How to Rename the File in Java
- How to Append to File in Java
- Read the File using BufferReader
- Read File using BufferInputStream
- Read the File using DataInputStream
- Reading a File in Java using BufferedInputStream
- Read a File in Java using BufferedReader
- Java Get File Extension From Filename
- Get File Size in Bytes KB MB GB TB
- How to Check if a File is Empty in Java
Comments
Post a Comment
Leave Comment