I'm struggling to solve an issue whereby a directory and its content is deleted and then later re-created by different process.
However, it seems as if a handle to the file is still kept open by the delete process, and results in an AccessDeniedException
being thrown when attempting to recreate. Any help would be greatly appreciated. Sample code as follows:
private static void deleteFilesAndDirectories(Path targetPath, Predicate<? super Path> filter) {
try {
try (Stream<Path> eligibleFiles = Files.walk(targetPath)
.filter(path -> !Files.isDirectory(path))
.filter(filter)) {
for (Path file : eligibleFiles.collect(Collectors.toList())) {
if (Files.isDirectory(file)) {
deleteFilesAndDirectories(file, filter);
}
Path parentDir = file.getParent();
Files.delete(file);
//Delete holding directory
if (Files.list(parentDir).count() == 0) {
Files.delete(parentDir);
}
}
}
} catch (IOException e) {
logger.error("Failed to delete directory"); //AccessDeniedException is caught
}
}
public static void delete(String subdirectory) {
deleteFilesAndDirectories(Paths.get(subdirectory), path -> true);
}
public static void store(MultipartFile file, String subdirectory) {
Path subdirectoryPath = Paths.get(subdirectory);
if (!Files.isDirectory(subdirectoryPath)) {
try {
Files.createDirectories(subdirectoryPath);
} catch (IOException e) {
throw new StorageException("Could not create sub-directory " + subdirectoryPath.toAbsolutePath(), e);
}
}
public static void main(String[] args) {
MultipartFile file = ...;
delete("mydir"); //Attempts to delete directory, but is still visible in Windows Explorer though access is denied when trying to go into it
store(file, "mydir"); //Checks if directory already exists, and attempts to create if not there.
}
Stacktrace printed when Files.createDirectories(subdirectoryPath)
is executed:
Caused by: java.nio.file.AccessDeniedException: D:\Workspaces\***\application\pending\0
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:83)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsFileSystemProvider.createDirectory(WindowsFileSystemProvider.java:504)
at java.nio.file.Files.createDirectory(Files.java:674)
at java.nio.file.Files.createAndCheckIsDirectory(Files.java:781)
at java.nio.file.Files.createDirectories(Files.java:767)