Deleting a temporary folder/file via deleteOnExit()

Another solution for deleting a temporary folder/file relies on the File.deleteOnExit() method. By calling this method, we can register for the deletion of a folder/file. The deletion action happens when JVM shuts down:

Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp");
String customDirPrefix = "logs_";
String customFilePrefix = "log_";
String customFileSuffix = ".txt";

try {
Path tmpDir = Files.createTempDirectory(
customBaseDir, customDirPrefix);
System.out.println("Created temp folder as: " + tmpDir);
Path tmpFile1 = Files.createTempFile(
tmpDir, customFilePrefix, customFileSuffix);
Path tmpFile2 = Files.createTempFile(
tmpDir, customFilePrefix, customFileSuffix);

try (DirectoryStream<Path> ds = Files.newDirectoryStream(tmpDir)) {
tmpDir.toFile().deleteOnExit();

for (Path file: ds) {
file.toFile().deleteOnExit();
}
} catch (IOException e) {
...
}

// simulate some operations with temp file until delete it
Thread.sleep(10000);
} catch (IOException | InterruptedException e) {
...
}
It is advisable to only rely on this method (deleteOnExit()) when the application manages a small number of temporary folders/files. This method may consume a lot of memory (it consumes memory for each temporary resource that's registered for deletion) and this memory may not be released until JVM terminates. Pay attention, since this method needs to be called in order to register each temporary resource, and the deletion takes place in reverse order of registration (for example, we must register a temporary folder before registering its content).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.26.22