Delete file using Java IO API
import java.io.File; publicclass Delete { publicstaticvoid main(String[] args) { String fileName = "file.txt"; // A File object to represent the filename File f = newFile(fileName); // Make sure the file or directory exists and isn't write protected if (!f.exists()) thrownew IllegalArgumentException( "Delete: no such file or directory: " + fileName); if (!f.canWrite()) thrownew IllegalArgumentException("Delete: write protected: " + fileName); // If it is a directory, make sure it is empty if (f.isDirectory()) { String[] files = f.list(); if (files.length > 0) thrownew IllegalArgumentException( "Delete: directory not empty: " + fileName); } // Attempt to delete it boolean success = f.delete(); if (!success) thrownew IllegalArgumentException("Delete: deletion failed"); } }
Related examples in the same category