Blog Archive

Java create temporary file using createTempFile methods

public static Path createTempFile(Path dir, String prefix, String suffix, FileAttribute... attrs) throws IOException
Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. The resulting Path is associated with the same FileSystem as the given directory.

Parameters:
  • dir - the path to directory in which to create the file
  • prefix - the prefix string to be used in generating the file's name; may be null
  • suffix - the suffix string to be used in generating the file's name; may be null, in which case ".tmp" is used
  • attrs - an optional list of file attributes to set atomically when creating the file
Returns:
  • the path to the newly created file that did not exist before this method was invoked

public static Path createTempFile(String prefix, String suffix, FileAttribute... attrs) throws IOException
Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. The resulting Path is associated with the default FileSystem.

Parameters:
  • prefix - the prefix string to be used in generating the file's name; may be null
  • suffix - the suffix string to be used in generating the file's name; may be null, in which case ".tmp" is used
  • attrs - an optional list of file attributes to set atomically when creating the file
Returns:
  • the path to the newly created file that did not exist before this method was invoked

Sample code to create Temp File in Java

try {
    Path tempFile = Files.createTempFile(null, ".myapp");
    System.out.format("The temporary file has been created: %s%n", tempFile);
} catch (IOException x) {
    System.err.format("IOException: %s%n", x);
}

2 comments :