# Create Temp Files Using Java NIO
# Description
According to the documentation of File.createTempFile(String, String)
(opens new window), a suitable alternative for creating temporary files in security-sensitive applications is to use java.nio.file.Files.createTempFile(String, String, FileAttribute<?>...)
(opens new window).
The reason behind it is that files created by the latter have more restrictive access permissions.
This rule replaces the temporary file creation using java.io.File
by the alternative methods defined in java.nio.file.Files
. Some detailed examples are provided below.
# Benefits
As mentioned in the javadocs (opens new window), the key benefit is security.
# Tags
# Code Changes
# Creating Temp File with Prefix and Suffix
Pre
File file = File.createTempFile("myFile", ".tmp");
Post
File file = Files.createTempFile("myFile", ".tmp").toFile();
# Creating Temp File in a new Parent Directory
Pre
File file = File.createTempFile("myFile", ".tmp", new File("/tmp/test/"));
Post
File file = Files.createTempFile(Paths.get("/tmp/test/"), "myFile", ".tmp").toFile();
# Creating Temp File in a Given Parent Directory
Pre
File directory = new File("/tmp/test/");
File file = File.createTempFile("myFile", ".tmp", directory);
Post
File directory = new File("/tmp/test/");
File file = Files.createTempFile(directory.toPath(), "myFile", ".tmp").toFile();
# Creating Temp File in a null
Parent Directory
Pre
File file = File.createTempFile("myFile", ".tmp", null);
Post
File file = Files.createTempFile("myFile", ".tmp").toFile();
Use a Java Refactoring Tool
No license required
You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.
System-wide Refactoring
Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.
# Properties
Property | Value |
---|---|
Rule ID | CreateTempFilesUsingJavaNIO |
First seen in jSparrow version | 3.21.0 |
Minimum Java version | 1.7 |
Remediation cost | 5 min |
Links |