Java 7 - How to delete a folder and its contents recursively
Java 7 New IO API - A program to Delete Directory including sub directories and files.
/**
* Java program to delete folder.
*/
package com.hadoop.test;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
/**
* @author Bala
*
*/
public class FileUtil {
private static boolean deleteFolder(String location) throws IOException{
java.nio.file.Path path = Paths.get(location);
Files.walkFileTree(path, new SimpleFileVisitor<java.nio.file.Path>(){
@Override
public FileVisitResult postVisitDirectory(java.nio.file.Path dir,
IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(java.nio.file.Path file,
BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
});
System.out.println("Deleted dir :" + location);
return true;
}
public static void main(String[] args) throws Exception{
deleteFolder("/path/to/folder");
}
}
Comments
Post a Comment