/** * Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories. * <p> * The difference between File.delete() and this method are: * <ul> * <li>A directory to be deleted does not have to be empty.</li> * <li>No exceptions are thrown when a file or directory cannot be deleted.</li> * </ul> * * @param path file or directory to delete, can be {@code null} * @return {@code true} if the file or directory was deleted, otherwise {@code false} */ public static boolean deleteQuietly(@Nullable Path path) { if (path == null) { return false; } try { if (path.toFile().isDirectory()) { deleteDirectory(path); } else { Files.delete(path); } return true; } catch (IOException | SecurityException ignored) { return false; } }
@Test public void deleteDirectory_does_not_fail_if_file_does_not_exist() throws IOException { File file = new File(temporaryFolder.newFolder(), "foo.d"); FileUtils.deleteDirectory(file); }
@Test public void deleteDirectory_throws_NPE_if_argument_is_null() throws IOException { expectDirectoryCanNotBeNullNPE(); FileUtils.deleteDirectory((File) null); }
@Test public void deleteDirectory_throws_IOE_if_file_is_symbolicLink() throws IOException { assumeTrue(SystemUtils.IS_OS_UNIX); Path folder = temporaryFolder.newFolder().toPath(); Path file1 = Files.createFile(folder.resolve("file1.txt")); Path symLink = Files.createSymbolicLink(folder.resolve("link1"), file1); assertThat(file1).isRegularFile(); assertThat(symLink).isSymbolicLink(); expectedException.expect(IOException.class); expectedException.expectMessage("Directory '" + symLink.toFile().getAbsolutePath() + "' is a symbolic link"); FileUtils.deleteDirectory(symLink.toFile()); }
@Test public void deleteDirectory_throws_IOE_if_argument_is_a_file() throws IOException { File file = temporaryFolder.newFile(); expectedException.expect(IOException.class); expectedException.expectMessage("Directory '" + file.getAbsolutePath() + "' is a file"); FileUtils.deleteDirectory(file); }
/** * Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories. * <p> * The difference between File.delete() and this method are: * <ul> * <li>A directory to be deleted does not have to be empty.</li> * <li>No exceptions are thrown when a file or directory cannot be deleted.</li> * </ul> * * @param path file or directory to delete, can be {@code null} * @return {@code true} if the file or directory was deleted, otherwise {@code false} */ public static boolean deleteQuietly(@Nullable Path path) { if (path == null) { return false; } try { if (path.toFile().isDirectory()) { deleteDirectory(path); } else { Files.delete(path); } return true; } catch (IOException | SecurityException ignored) { return false; } }