Java Delete a file

Java Delete a file

In Java, you can delete a file using the java.io.File class and its delete method.

Here is an example of how to delete a file in Java:

import java.io.File;

public class Main {
  public static void main(String[] args) {
    // Create a File object for the file to be deleted
    File file = new File("C:\\path\\to\\file.txt");

    // Delete the file
    if (file.delete()) {
      System.out.println("File deleted successfully.");
    } else {
      System.out.println("Failed to delete file.");
    }
  }
}
Sour‮ww:ec‬w.lautturi.com

This code creates a File object for the file to be deleted, and then calls the delete method on the object. If the file is deleted successfully, the delete method returns true; otherwise, it returns false.

Keep in mind that the delete method will only work if the file exists and the Java process has the necessary permissions to delete it. If the file does not exist, or if the Java process does not have the necessary permissions, the delete method will return false and the file will not be deleted.

You can also use the java.nio.file.Files class and its delete method to delete a file in Java. Here is an example:

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

public class Main {
  public static void main(String[] args) {
    // Create a Path object for the file to be deleted
    Path filePath = Paths.get("C:\\path\\to\\file.txt");

    try {
      // Delete the file
      Files.delete(filePath);
      System.out.println("File deleted successfully.");
    } catch (IOException e) {
      System.out.println("Failed to delete file.");
      e.printStackTrace();
    }
  }
}

This code creates a Path object for the file to be deleted, and then calls the delete method from the Files class. If the file is deleted successfully, the delete method does not throw an exception; otherwise, it throws an IOException, which you must handle or declare in your code.

Note that the delete method from the Files class is a more flexible and powerful way to delete a file, as it supports various options and modes. For example, you can use the deleteIfExists method to delete a file only if it exists, or you can use the NOFOLLOW_LINKS option to delete a symbolic link without deleting the target file.

Created Time:2017-11-03 00:14:40  Author:lautturi