1. Introduction
The createTempFile() method creates an empty file in the temporary directory which commonly is a /tmp
or /var/tmp
in Linux and C:\Users\<username>\AppData\Local\Temp
in Windows. The method accepts also the third parameter where we can specify a different folder in which the file will be generated. Two first parameters are prefix and suffix that will be used for generating the file's name. Note that the prefix and the suffix may first be adjusted to fit the limitations of the operating system. The name of the new file will be generated by concatenating the prefix, five or more internally-generated characters, and the suffix.
2. Method signature
createTempFile takes two or three parameters. The third parameter is a directory in which the file will be generated.
createTempFile(prefix, suffix, null)
is the same as createTempFile(prefix, suffix)
.
Parameters:
- prefix - prefix string to be used in generating the file's name; this argument must be at least three characters long
suffix - suffix string to be used in generating the file's name; if null then the default suffix ".tmp" will be used
directory - directory in which the file should be created, if this parameter is null the default temporary folder will be used
Returns
- File - a newly-created empty file
Throws
- IllegalArgumentException - if the prefix parameter contains fewer than three characters
- IOException - in case the file could not be created
- SecurityException - when security manager does not allow to create a file
3. Examples
3.1. The program that creates an empty file in the temporary directory
The output:
3.2. Program that creates file using createTempFile()
in /var/tmp
directory
The output:
4. Conclusion
In this article we presented File.createTempFile()
a method that creates an empty file in a temporary directory. We can use this method also to generate a file in any other directory, using the third parameter. Creating and using temporary files are common operations used in complex systems where we must store a partially computed date on the filesystem to improve performance.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}