Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java java.nio.file.Files createTempFile() Method

Java java.nio.file.Files createTempFile() Method

Java File Java java.nio.file.Files


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

- Type: `String` - Description: The prefix part of the temporary file name. Must contain at least 3 characters. - Examples: `"temp_"`, `"myapp_"` - Type: `String` - Description: The suffix part of the temporary file name (usually the file extension). If `null`, it defaults to `.tmp`. - Examples: `".txt"`, `".log"` - 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

- Type: `Path` - Description: Specifies the directory in which the temporary file is created. If `null`, the system's default temporary file directory is used. - Examples: `Paths.get("/tmp")`, `Paths.get("C:\\Temp")`

Return Value

Exception handling

createTempFile() The method may throw the following exceptions:


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

  1. File deletion:

  2. Temporary files are not deleted automatically; the program must explicitly delete them or configure deletion on JVM exit.
  3. You can use the tempFile.toFile().deleteOnExit() to let the JVM automatically delete the file on exit.
  4. - Temporary files are not deleted automatically; the program must explicitly delete them or configure deletion on JVM exit. - You can use `tempFile.toFile().deleteOnExit()` to let the JVM automatically delete the file on exit.
    1. Safety:

    2. Ensure that the prefix and suffix of the temporary file name do not cause security issues (such as directory traversal attacks).
    3. In sensitive scenarios, consider setting appropriate file permissions.
    4. - Ensure that the prefix and suffix of the temporary file name do not cause security issues (such as directory traversal attacks). - In sensitive scenarios, consider setting appropriate file permissions.
      1. Cross-platform compatibility:

      2. File attributes (such as POSIX permissions) behave differently on different operating systems.
      3. The Windows system does not support POSIX file permissions.
      4. - File attributes (such as POSIX permissions) behave differently on different operating systems. - The Windows system does not support POSIX file permissions.
        1. Concurrent Access:

        2. When creating temporary files in a multi-threaded environment, ensure that file names do not conflict.
        3. - When creating temporary files in a multi-threaded environment, ensure that file names do not conflict.

          Best Practices

          1. Using try-with-resources:

          Example

          try (InputStream is = Files.newInputStream(tempFile)) {
              // Use temporary files
          } catch (IOException e) {
              e.printStackTrace();
          } finally {
              Files.deleteIfExists(tempFile); // Ensure the file is deleted
          }
          2.

          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.
          1. Resource cleanup:

          2. For long-running applications, periodically clean up temporary files that are no longer in use.
          3. - For long-running applications, periodically clean up temporary files that are no longer in use.

            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 File Java java.nio.file.Files