Files.createTempFile() and Files.createTempDirectory()
NIO.2 provides secure and convenient methods to create temporary files and directories with appropriate permissions and unique names.
How it Works
You can specify a prefix, suffix, and optional directory. If no directory is provided, it uses the system's default temporary folder (e.g., /tmp or %TEMP%).
Java Example
import java.nio.file.*;
import java.io.IOException;
public class TempFileExample {
public static void main(String[] args) throws IOException {
Path tempFile = Files.createTempFile("myapp_", ".log");
System.out.println("Temp file: " + tempFile);
Files.deleteIfExists(tempFile);
}
}
Output
Temp file: C:\Users\...\myapp_12345.log
Key Points
- Secure temp file creation
- Automatic unique naming
- Supports custom prefix and suffix
- Can specify parent directory
Comments