Writing to a Temporary File
The javax.servlet.context.tempdir attribute maps to a temporary directory where short-lived working files can be stored. Each context receives a different temporary directory. For the previous example, the directory is server_root/work/localhost_8080. Example 4-4 shows how to write to a temporary file in the temporary directory.
Example 4-4. Creating a Temporary File in a Temporary Directory
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// The directory is given as a File object
File dir = (File) getServletContext()
.getAttribute("javax.servlet.context.tempdir");
// Construct a temp file in the temp dir (JDK 1.2 method)
File f = File.createTempFile("xxx", ".tmp", dir);
// Prepare to write to the file
FileOutputStream fout = new FileOutputStream(f);
// ...
}
First, this servlet locates its temporary directory. Then, it uses the createTempFile( ) method to create a temporary file in that directory with an xxx prefix and .tmp suffix. Finally, it constructs a FileOutputStream to write to the temporary file. Files that must persist between server restarts should not be placed in the temporary directory.