I want to create and delete a directory using Java, but it isn\'t working.
File index = new File(\"/home/Work/Indexer1\");
if (!index.exists()) {
index.m
You may also use this to delete a folder that contains subfolders and files.
Fist, create a recursive function.
private void recursiveDelete(File file){
if(file.list().length > 0){
String[] list = file.list();
for(String is: list){
File currentFile = new File(file.getPath(),is);
if(currentFile.isDirectory()){
recursiveDelete(currentFile);
}else{
currentFile.delete();
}
}
}else {
file.delete();
}
}
then, from your initial function use a while loop to call the recursive.
private boolean deleteFolderContainingSubFoldersAndFiles(){
boolean deleted = false;
File folderToDelete = new File("C:/mainFolderDirectoryHere");
while(folderToDelete != null && folderToDelete.isDirectory()){
recursiveDelete(folderToDelete);
}
return deleted;
}
I like this solution the most. It does not use 3rd party library, instead it uses NIO2 of Java 7.
/**
* Deletes Folder with all of its content
*
* @param folder path to folder which should be deleted
*/
public static void deleteFolderAndItsContent(final Path folder) throws IOException {
Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (exc != null) {
throw exc;
}
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
You can use FileUtils.deleteDirectory. JAVA can't delete the non-empty foldres with File.delete().
Java isn't able to delete folders with data in it. You have to delete all files before deleting the folder.
Use something like:
String[]entries = index.list();
for(String s: entries){
File currentFile = new File(index.getPath(),s);
currentFile.delete();
}
Then you should be able to delete the folder by using index.delete()
Untested!