As part of a recent project, I had a need to generate classes to a temporary directories. Currently, this was being done by a simple File-based path. However, that has two downfalls: the paths are tied to the implementation of the application server and files may be blocked in the application server. However, JSPs do this all the time by storing their resulting classes to the work or temporary directory in the application. I had to search several variants of keywords to find my answer, but the servlet spec actually has the notion of a work directory for this type of work. You access the directory through the
ServletContext.getAttribute method. In servlet spec 2.5 and below, the static constant TEMPDIR is not defined. Instead, you use the constant
javax.servlet.context.tempdir. The returned value is of type
java.io.File that you can use as the base directory. For example,
With this, the test file will be stored in the working directory of the deployed web application. Note that files stored are temporary and may or may not be preserved across restarts. The servlet container manages the actual files once the application is shutdown.