Java Example - Creating a Temporary File
The following example demonstrates how to use the File class's createTempFile(String prefix, String suffix) method to create a temporary file in the default temporary directory, where the parameter prefix is the prefix and suffix is the suffix:
Main.java File
import
java
.
io
.*;
public
class
Main
{
public
static
void
main
(
String
[
]
args
)
throws
Exception
{
File
temp
=
File
.
createTempFile
(
"
testrunoobtmp
"
,
"
.txt
"
)
;
System
.
out
.
println
(
"
File path:
"
temp
.
getAbsolutePath
(
)
)
;
temp
.
deleteOnExit
(
)
;
BufferedWriter
out
=
new
BufferedWriter
(
new
FileWriter
(
temp
)
)
;
out
.
write
(
"
aString
"
)
;
System
.
out
.
println
(
"
Temporary file created:
"
)
;
out
.
close
(
)
;
}
}
You can also use the directory parameter in createTempFile(String prefix, String suffix, File directory) to specify the directory of the temporary file:
Main.java File
import
java
.
io
.
File
;
public
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
File
f
=
null
;
try
{
//
Create temporary file
f
=
File
.
createTempFile
(
"
tmp
"
,
"
.txt
"
,
new
File
(
"
C:/
"
)
)
;
//
Output absolute path
System
.
out
.
println
(
"
File path:
"
f
.
getAbsolutePath
(
)
)
;
//
Delete the temporary file after termination
f
.
deleteOnExit
(
)
;
//
Create temporary file
f
=
File
.
createTempFile
(
"
tmp
"
,
null
,
new
File
(
"
D:/
"
)
)
;
//
Output absolute path
System
.
out
.
(
"
File path:
"
f
.
getAbsolutePath
(
)
)
;
//
Delete the temporary file after termination
f
.
deleteOnExit
(
)
;
}
catch
(
Exception
e
)
{
//
If there is any error output
e
.
printStackTrace
(
)
;
}
}
}
Java Examples