Add FileUtils.delete(File), refactor, reuse.
Javadoc.
MODIFY
src/changes/changes.xml
src/changes/changes.xml
@@ -115,6 +115,9 @@ The <action> type attribute can be add,update,fix,remove.
<action dev="ggregory" type="add" due-to="Gary Gregory">
Add FileSystem#supportsDriveLetter().
</action>
+ <action dev="ggregory" type="add" due-to="Gary Gregory">
+ Add FileUtils.delete(File).
+ </action>
<!-- UPDATES -->
<action dev="ggregory" type="update" due-to="Dependabot">
Update junit-jupiter from 5.6.2 to 5.7.0 #153.

MODIFY
src/main/java/org/apache/commons/io/FileDeleteStrategy.java
src/main/java/org/apache/commons/io/FileDeleteStrategy.java
@@ -135,16 +135,17 @@ public boolean deleteQuietly(final File fileToDelete) {
* A check has been made to ensure that the file will exist.
* </p>
* <p>
- * This implementation uses {@link File#delete()}.
+ * This implementation uses {@link FileUtils#delete(File)}.
* </p>
*
- * @param fileToDelete the file to delete, exists, not null
+ * @param file the file to delete, exists, not null
* @return true if the file was deleted
* @throws NullPointerException if the file is null
* @throws IOException if an error occurs during file deletion
*/
- protected boolean doDelete(final File fileToDelete) throws IOException {
- return fileToDelete.delete();
+ protected boolean doDelete(final File file) throws IOException {
+ FileUtils.delete(file);
+ return true;
}
/**

MODIFY
src/main/java/org/apache/commons/io/FileUtils.java
src/main/java/org/apache/commons/io/FileUtils.java
@@ -1108,6 +1108,22 @@ static String decodeUrl(final String url) {
return decoded;
}
+ /**
+ * Deletes the given File but throws IOException if it cannot, unlike {@link File#delete()}.
+ *
+ * @param file The file to delete.
+ * @return the given file.
+ * @throws IOException if the file cannot be deleted.
+ * @see File#delete()
+ * @since 2.9.0
+ */
+ public static File delete(final File file) throws IOException {
+ if (!file.delete()) {
+ throw new IOException("Unable to delete " + file);
+ }
+ return file;
+ }
+
/**
* Deletes a directory recursively.
*
@@ -1124,9 +1140,7 @@ public static void deleteDirectory(final File directory) throws IOException {
cleanDirectory(directory);
}
- if (!directory.delete()) {
- throw new IOException("Unable to delete directory " + directory + ".");
- }
+ delete(directory);
}
/**

MODIFY
src/test/java/org/apache/commons/io/FileUtilsTestCase.java
src/test/java/org/apache/commons/io/FileUtilsTestCase.java
@@ -1331,6 +1331,12 @@ public void testDeleteDirectoryWithNonDirectory() throws Exception {
}
}
+ @Test
+ public void testDelete() throws Exception {
+ assertEquals(testFile1, FileUtils.delete(testFile1));
+ assertThrows(IOException.class, () -> FileUtils.delete(new File("does not exist.nope")));
+ }
+
@Test
public void testDeleteQuietlyDir() throws IOException {
final File testDirectory = new File(temporaryFolder, "testDeleteQuietlyDir");

Add FileUtils.delete(File), refactor, reuse.

Javadoc.