# Create Temp Files Using Java NIO

# Properties

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

# Description

According to the documentation of File.createTempFile(String, String), a suitable alternative for creating temporary files in security-sensitive applications is to use java.nio.file.Files.createTempFile(String, String, FileAttribute<?>...). 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, the key benefit is security.

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

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version:

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊