Java java.nio.file.Files createTempFile() Method
createTempFile() method is used to create a new empty file in a specified directory or the default temporary file directory. The method has multiple overloaded versions, providing different parameter combinations to meet different needs.
Method Definition
public
static
Path createTempFile
(
String
prefix,
String
suffix, FileAttribute
...
attrs
)
throws
IOException
public
static
Path createTempFile
(
Path dir,
String
prefix,
String
suffix, FileAttribute
...
attrs
)
throws
IOException
Parameter Description
1. Basic parameters
-
prefix(prefix): - Type:
String - Description: The prefix part of the temporary file name. Must contain at least 3 characters.
- Example:
"temp_","myapp_"
-
suffix(suffix): - Type:
String - Description: The suffix part of the temporary file name (usually the file extension). If
null, it defaults to.tmp. - Example:
".txt",".log"
-
attrs(file attributes): - Type:
FileAttribute>...(variable arguments) - Description: Optional file attributes used to set the file's permissions, owner, etc.
- Example:
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-r-----"))
2. Directory parameter
dir(directory path):- Type:
Path - Description: Specifies the directory in which the temporary file is created. If
null, the system's default temporary file directory is used. - Example:
Paths.get("/tmp"),Paths.get("C:\\Temp")
Return Value
- Return Type:
Path - Description: Returns the path object of the newly created temporary file.
Exception handling
createTempFile() The method may throw the following exceptions:
IOException: If an I/O error occurs, such as failure to create the file or insufficient permissions.IllegalArgumentException: IfprefixorsuffixThe parameters do not meet the requirements.UnsupportedOperationException: If the specified file attributes are not supported.
Usage examples
Example 1: Create a default temporary file
Example
import
java.io.IOException
;
import
java.nio.file.Files
;
import
java.nio.file.Path
;
public
class
TempFileExample1
{
public
static
void
main
(
String
[
]
args
)
{
try
{
// Create a temporary file (using the default temporary directory)
Path tempFile
=
Files.
createTempFile
(
"myapp_"
,
".tmp"
)
;
System
.
out
.
println
(
"Temporary file path: "
tempFile.
toAbsolutePath
(
)
)
;
}
catch
(
IOException
e
)
{
e.
printStackTrace
(
)
;
}
}
}
Output example:
临时文件路径: /tmp/myapp_123456789.tmp
Example 2: Create a temporary file in a specified directory
Example
import
java.io.IOException
;
import
java.nio.file.Files
;
import
java.nio.file.Path
;
import
java.nio.file.Paths
;
public
class
TempFileExample2
{
public
static
void
main
(
String
[
]
args
)
{
try
{
// Specify the temporary file directory
Path tempDir
=
Paths.
get
(
"/tmp/custom_temp"
)
;
// Create the temporary file
Path tempFile
=
Files.
createTempFile
(
tempDir,
"data_"
,
".csv"
)
;
System
.
out
.
println
(
"Temporary file path: "
tempFile.
toAbsolutePath
(
)
)
;
}
catch
(
IOException
e
)
{
e.
printStackTrace
(
)
;
}
}
}
Output example:
临时文件路径: /tmp/custom_temp/data_987654321.csv
Example 3: Set file attributes (Linux/Unix systems)
Example
import
java.io.IOException
;
import
java.nio.file.Files
;
import
java.nio.file.Path
;
import
java.nio.file.attribute.PosixFilePermission
;
import
java.nio.file.attribute.PosixFilePermissions
;
import
java.util.Set
;
public
class
TempFileExample3
{
public
static
void
main
(
String
[
]
args
)
{
try
{
// Set file permissions (POSIX-compliant systems only)
Set
<
PosixFilePermission
permissions
=PosixFilePermissions.
fromString
(
"rw-r-----"
)
;
FileAttribute
<
Set
<
PosixFilePermission
attr
=PosixFilePermissions.
asFileAttribute
(
permissions
)
;
// Create a temporary file with specific permissions
Path tempFile
=
Files.
createTempFile
(
"secure_"
,
".dat"
, attr
)
;
System
.
out
.
println
(
"Temporary file path: "
tempFile.
toAbsolutePath
(
)
)
;
}
catch
(
IOException
e
)
{
e.
printStackTrace
(
)
;
}
}
}
Output example:
临时文件路径: /tmp/secure_456789123.dat
Notes
-
File deletion:
tempFile.toFile().deleteOnExit() to let the JVM automatically delete the file on exit.-
Safety:
-
Cross-platform compatibility:
-
Concurrent Access:
Best Practices
-
Using try-with-resources:
Example
// Use temporary files
} catch (IOException e) {
e.printStackTrace();
} finally {
Files.deleteIfExists(tempFile); // Ensure the file is deleted
}
Naming Convention:
- Use meaningful file name prefixes for easier debugging and maintenance.
- Avoid using overly simple suffixes (such as
.tmp), and use specific suffixes based on the file content.
-
Resource cleanup:
Through the detailed explanation and examples above, you should have mastered java.nio.file.Files.createTempFile() method's usage and precautions. This method is very practical in scenarios that require temporary data storage; used properly, it can greatly improve the robustness and security of the program.
Java java.nio.file.Files