JSP and Servlet That Reads a File / Writes a File

First, let's first describe reading a file. Both this JSP and the file 'test.txt' are in the root directory of the Web Application, at the same level as WEB-INF.

<%@ page import="java.io.*" %>
<%
   try{
      String fileName = application.getRealPath("/test.txt");
FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr);
      String line;
      while ((line = br.readLine()) != null){
         out.println(line);
      }
   }catch (Exception e){
      out.println("error: " + e.getMessage());
   }
%> 

Here is a Servlet that does the same thing:

//set classpath for compile with . loc_setClasspat in $ROOT/etc directory
//do compile with javac ReadServlet.java
//restart the Jrun server
//in browser, http://server:port//servlet/TestServlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ReadServlet extends HttpServlet {
 private ServletConfig config;
 private ServletContext application;
 public void service (ServletRequest req , ServletResponse res) throws IOException {
   if (config == null){
      config = getServletConfig();
      application = config.getServletContext();
   }
   res.setContentType("text/html");
   PrintWriter out = res.getWriter();
   try{
      String fileName = application.getRealPath("/test.txt"); 
      FileReader fr = new FileReader(fileName); 
      BufferedReader br = new BufferedReader(fr); String line;
      while ((line = br.readLine()) != null){
          out.println(line);
      }
      }catch (Exception e){
         out.println("error: " + e.getMessage());
      }
   }
}

Next, here's a JSP that writes to a file:

<%@ page import="java.io.*" %>
<%
out.println("starting");
try{
//new file is in the root directory of the Web Application
String fileName = application.getRealPath("/new.txt");
FileWriter fw = new FileWriter(fileName);
BufferedWriter bw = new BufferedWriter(fw); String line;
PrintWriter pw = new PrintWriter(bw);
pw.println("one");
pw.println("two");
pw.close();
out.println("done");
}catch (Exception e){
out.println("error: " + e.getMessage());
}

%>

In older versions of Jrun (2.3), the application object may not be provided, so then you might
have to generate it yourself:

<%@ page import="java.io.*" %>
<%
try {
ServletConfig conf = getServletConfig();
ServletContext app = conf.getServletContext();
      out.println("starting");
      //new file is in the root directory of the Web Application
      String fileName = app.getRealPath("/new.txt");
      FileWriter fw = new FileWriter(fileName);
      BufferedWriter bw = new BufferedWriter(fw); 
      String line;
      PrintWriter pw = new PrintWriter(bw);
      pw.println("one");
      pw.println("two");
      pw.close();
      out.println("done");
   }catch (Exception e){
      out.println("error: " + e.getMessage());
   }
%>