# 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();

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID CreateTempFilesUsingJavaNIO
First seen in jSparrow version 3.21.0
Minimum Java version 1.7
Remediation cost 5 min
Links