Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Java Delete Files


Java Delete Files

In Java, you can delete files using the java.io.File class or the java.nio.file.Files class. Both approaches provide methods to delete files. Here's how you can delete files using each approach:

Deleting Files with java.io.File

import java.io.File;

public class DeleteFile {
    public static void main(String[] args) {
        File file = new File("example.txt");
        
        // Check if file exists before deleting
        if (file.exists()) {
            if (file.delete()) {
                System.out.println("File deleted successfully.");
            } else {
                System.out.println("Failed to delete the file.");
            }
        } else {
            System.out.println("File doesn't exist.");
        }
    }
}
      

Deleting Files with java.nio.file.Files

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;

public class DeleteFileNIO {
    public static void main(String[] args) {
        Path path = Paths.get("example.txt");
        
        try {
            Files.delete(path);
            System.out.println("File deleted successfully.");
        } catch (IOException e) {
            System.out.println("Failed to delete the file: " + e.getMessage());
        }
    }
}
      

Notes:

Differences:



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java