# 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


File file = File.createTempFile("myFile", ".tmp");


File file = Files.createTempFile("myFile", ".tmp").toFile();

# Creating Temp File in a new Parent Directory


File file = File.createTempFile("myFile", ".tmp", new File("/tmp/test/"));


File file = Files.createTempFile(Paths.get("/tmp/test/"), "myFile", ".tmp").toFile();

# Creating Temp File in a Given Parent Directory


File directory = new File("/tmp/test/");
File file = File.createTempFile("myFile", ".tmp", directory);


File directory = new File("/tmp/test/");
File file = Files.createTempFile(directory.toPath(), "myFile", ".tmp").toFile();

# Creating Temp File in a null Parent Directory


File file = File.createTempFile("myFile", ".tmp", null);


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.

a drawn cute bird pointing at a graph that shows positive results

# Properties

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