Background
Well lately I have written a lot of code for file manipulation, I/O etc. So let me take this post to show how can we create or delete directories. Well Java provides APIs for them so it should be pretty straightforward to understand. Important point to look forward is that if you are deleting a directory and it has more files in it then the directory will not get deleted unless all it's children are deleted recursively. Note File as a Java object can represent either a file or a directory. You can use File 's class isDirectory() method Eg.
File file = new File("C:\\Users\\athakur\\Downloads"); if(file.isDirectory()) { System.out.println("File is a directory"); }
Creating a File
To create a file we can use createNewFile() method. Eg -
File file = new File("C:\\Users\\athakur\\Downloads\\abc.txt"); if(!file.exists()) { file.createNewFile(); }
Creating a Directory
To create a directory first create a File object and then call mkdir() on it. Eg -
File file = new File("C:\\Users\\athakur\\Downloads\\Movies"); if(!file.exists()) { file.mkdir(); }
Deleting a file/directory
To delete a file or a directory we have to use delete() method. As stated in introductory paragraph if directory has data that data needs to be deleted first. "rm -rf *" does not work in java :).
public void deleteDirectory(String path) { File file = new File(path); if(file.isDirectory()){ String[] childFiles = file.list(); if(childFiles == null) { //Directory is empty. Proceed for deletion file.delete(); } else { //Directory has other files. //Need to delete them first for (String childFilePath : childFiles) { //recursive delete the files deleteDirectory(childFilePath); } } } else { //it is a simple file. Proceed for deletion file.delete(); } }
Above method will delete complete directory.