In this tutorial we will go over all steps in details to delete Files and Folders on Windows OS, Mac OS X and Linux.
Here I
- Create file DeleteWindowsFileFolder.java
- Create
crunchifyDeleteWindowsFolder(List of Directories)
which first check for if directory exists or not? If exists then it will delete all files under it. - Create
crunchifyDeleteFiles(file)
which deletes file.
package Pack;
import java.io.File;
import java.io.IOException;
/**
* @author Rajkumar Sahoo
*
*/
public class DeleteWindowsFileFolder {
public static void main(String[] args) {
// For Windows Provide Location: c:\\crunchify, c:\\temp
// For Mac OS X Provide Location: /Users/<username>/Downloads/file.ppsx
// For Linux Provide Location: /tmp/crunchify-file.txt
String[] crunchifyDir = { "D:\\crunchify", "c:\\temp", "/Users/<username>/Downloads/file.ppsx",
"/tmp/crunchify-file.txt" };
String result = crunchifyDeleteWindowsFolder(crunchifyDir);
System.out.println("Result: " + result);
}
public static void crunchifyDeleteFiles(File myFile) throws IOException {
if (myFile.isDirectory()) {
// Returns an array of strings naming the files and directories in the directory denoted by this abstract
// pathname.
String crunchifyFiles[] = myFile.list();
for (String file : crunchifyFiles) {
// Creates a new File instance from a parent abstract pathname and a child pathname string.
File fileDelete = new File(myFile, file);
// recursion
crunchifyDeleteFiles(fileDelete);
}
} else {
// Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory,
// then the directory must be empty in order to be deleted.
myFile.delete();
System.out.println("File is deleted : " + myFile.getAbsolutePath());
}
}
public static String crunchifyDeleteWindowsFolder(String[] crunchifyDirectories) {
try {
for (String crunchifyDir : crunchifyDirectories) {
File directory = new File(crunchifyDir);
// Tests whether the file or directory denoted by this abstract pathname exists.
if (!directory.exists()) {
System.out.println("File does not exist: " + directory);
} else {
try {
// recursion approached
crunchifyDeleteFiles(directory);
System.out.println("Cleaned Up Files Under Directory: " + directory + "\n");
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
}
return "Execution Complete";
} catch (Exception e) {
return "Execution Failed";
}
}
}
Output :
File is deleted : D:\crunchify\New Microsoft Word Document.docx
Cleaned Up Files Under Directory: D:\crunchify
File does not exist: c:\temp
File does not exist: \Users\<username>\Downloads\file.ppsx
File does not exist: \tmp\crunchify-file.txt
Result: Execution Complete
0 comments:
Post a Comment