How to remove the file by using file name in java ?

To remove a file using its name in Java, you can use the java.io.File class. Here's an example:

import java.io.File;

public class RemoveFileExample {

    public static void main(String[] args) {

        // Specify the path and name of the file to be deleted

        String fileName = "file.txt";

        String filePath = "/path/to/file/" + fileName;

        

        // Create a File object representing the file to be deleted

        File file = new File(filePath);

        

        // Check if the file exists

        if (file.exists()) {

            // Attempt to delete the file

            boolean success = file.delete();

            

            if (success) {

                System.out.println("File successfully deleted.");

            } else {

                System.out.println("Failed to delete the file.");

            }

        } else {

            System.out.println("The file does not exist.");

        }

    }

}


In this example, we first specify the name and path of the file to be deleted. We then create a File object representing the file, and use the exists() method to check if it exists. If the file exists, we attempt to delete it using the delete() method. The delete() method returns a boolean value indicating whether the file was successfully deleted or not.


Comments