Learn to create a temporary file and write to it in Java. We will use the code sample used for creating a temporary file example.
1. Writing Char Data using BufferedWriter with FileWriter
The FileWriter
class can be used for writing character files. Wrapping a BufferedWriter
around FileWriter increases the performance of the operation.
FileWriter fw = null;
BufferedWriter bw = null;
try {
File tempFile = File.createTempFile("data", ".txt");
fw = new FileWriter(tempFile);
bw = new BufferedWriter(fw);
bw.write("This is the temporary data written to temp file");
} catch (IOException e) {
e.printStackTrace();
}
finally {
fw.close();
bw.close();
}
2. Writing Bytes using Files.write()
The write()
method does the simple thing. It writes bytes to a file. By default, if the temp file does not exist, it will create a new file else overwrites an existing file.
- To append to an existing temporary file, use
StandardOpenOption.APPEND
option while writing the content. - Due to usage of
deleteOnExit()
, the file will be deleted when the program exits.
try {
final Path path = Files.createTempFile("myTempFile", ".txt");
// Writing data here
byte[] buf = "some data".getBytes();
Files.write(path, buf);
// For appending to the existing file
// Files.write(path, buf, StandardOpenOption.APPEND);
// Delete file on exit
path.toFile().deleteOnExit();
} catch (IOException e) {
e.printStackTrace();
}
Happy Learning !!
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
Hi Gupta,
Please answer for following question,
What is the expired time for Temp file, is there any time limit or not, if “Yes” please let me know how much time or shall we set Temp file time ,or if “Not” please let me know what is the exact meaning of Temp File.
Java docs say – Files.createTempFile() method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit() method.
In the NIO example, where is “file” defined?
The example can’t be compiled.
OOPs.. typo. Use path instead. Corrected in program. Thanks for noticing.