Here you can find the source of deleteLocalFileOrDirectory(File file)
Parameter | Description |
---|---|
file | file or directory to delete. |
Parameter | Description |
---|---|
Exception | if there are any errors. |
public static void deleteLocalFileOrDirectory(File file) throws Exception
//package com.java2s; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; public class Main { /**/* ww w . ja v a2 s . co m*/ * Delete a local file or directory. * Directories will be deleted recursively. * * @param file file or directory to delete. * @throws Exception if there are any errors. */ public static void deleteLocalFileOrDirectory(File file) throws Exception { if (file.isFile()) { Files.delete(file.toPath()); } else if (file.isDirectory()) { deleteLocalDirectory(file); } } /** * Recursively delete a local directory. * * @param directory the directory to delete. * @throws Exception if directory is not a directory, or if there are any errors. */ public static void deleteLocalDirectory(File directory) throws Exception { if (!directory.isDirectory()) { throw new Exception("File " + directory.getAbsolutePath() + " is not a directory."); } Files.walkFileTree(directory.toPath(), 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 e) throws IOException { if (e == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { // directory iteration failed throw e; } } }); } }