Sample Application: Delete File
This function implements deleting a single file. The name of the file to be deleted is passed as an argument to the function.
The function first creates a file handler for the given file . and checks whether the file exists. If not an error message saying that such a file does not exist is displayed. If the file exists the file is deleted and displays message as file deleted.
// -----------------------------------------------------------------------------
// FileDelete.java
// -----------------------------------------------------------------------------
import java.io.File;
public class FileDelete {
/**
* ---------------------------------------------------------------------
* This function deletes the file specified
*
* File file holds the file object to be deleted
*
* @param fileName mapping name of the file to be deleted
* @return boolean value
*
* ---------------------------------------------------------------------
**/
public static boolean deleteFile(String fileName) {
try {
// Construct a File object for the file to be deleted.
File file = new File(fileName);
// Checks if the file exists
if (!file.exists()) {
System.err.println("File " + fileName+ " does not exist");
return false;
}
// Deleting the file
if (file.delete())
System.err.println("** Deleted " + fileName + " **");
else
System.err.println("Failed to delete " + fileName);
return true;
} catch (SecurityException e) {
System.err.println("Unable to delete " + fileName + "(" + e.getMessage() + ")");
return false;
}
}
}
FileDelete.java deletes the given file and displays appropriate message.