In some cases, you might write data from a servlet to a file, rather than send output to an HTTP request. You can use the file to store temporary data or as a persistence mechanism. This section describes how to write files to the web application's directory and to a temporary directory generated by JRun for hot-deployed web applications.
You can use the servlet context to get a path to the web application's root directory, which is /jrun_root/servers/web_app_name. Then, you can write the file in that directory, because the JRun server has write permissions by default.
The following example prints a simple string to a file and stores it in the web application's root directory:
...
Properties sysprops = System.getProperties();
String c = sysprops.getProperty("file.separator");
PrintWriter out = response.getWriter();
String notes = "this is the string";
String filename = "file.txt";
String path = new String();
try {
ServletContext sc = this.getServletContext();
path = sc.getRealPath("/");
FileOutputStream fos = new FileOutputStream(path + c + filename);
byte[] bytes = notes.getBytes();
fos.write(bytes);
out.println("Created " + filename + " in " + path);
} catch (Exception e) {
out.println(e.toString());
}
...
To see a sample servlet, start the samples JRun server and open a browser to http://localhost:8200/techniques.
When you use the hot deploy feature in JRun by putting a WAR or EAR file in the JRun server's root directory, JRun creates a temporary directory in /jrun_root/servers/server_name/SERVER-INF/temp/application_name-temp that stores temporary information. You can access this directory by getting the javax.servlet.context.tempdir attribute. You also can write a file to that directory using the following example:
...
ServletContext context = this.getServletContext();
Properties sysprops = System.getProperties();
String c = sysprops.getProperty("file.separator");
try {
File baseDir = (File) context.getAttribute("javax.servlet.context.tempdir");
String fullpath = baseDir.getAbsolutePath() + c + "settings.txt";
File f = new File(fullpath);
FileOutputStream fout = null;
fout = new FileOutputStream(fullpath);
sysprops.store(fout, null);
out.println("The following file has been created: " + f.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
...
This code example uses the ServletContext to get the web application's temporary directory and the System object's properties to get the file separator. It stores the system properties in a file named settings.txt.
To see a sample servlet, start the samples JRun server and open a browser to http://localhost:8200/techniques.