/*
 * Author: Don West, NCF Java Team, IBM, RTP, NC.
 * Date written: 6/23/97.
 *
 * This is a servlet that reads a file and writes the file to 
 * the browser page. The file name must be an absolute pathname.
 * The file name is input via a query string parameter value.
 */

import javax.servlet.*;
import java.io.*;

/**
  * Example FileToBrowserServlet -- Demonstrates basic file I/O 
  * techniques.
  */

public class FileToBrowserServlet extends GenericServlet
{
    /**
      * @param req Instance of class ServletRequest.
      * @param res Instance of class ServletResponse.
      * @exception IOException When opening or reading from
      * the input file or writing to the output stream.
      */ 
        public void service(ServletRequest req, ServletResponse res)
                throws IOException
        {
                char c;
                String fileParam;
                String lineIn;
                BufferedReader fileIn;

                res.setContentType("text/plain"); 
                ServletOutputStream os = res.getOutputStream();

        try
        {
                   /* get the file parameter from the query string */
                   fileParam = req.getParameter("file");
                
                   /* open the file for reading and set the file
                      pointer to the beginning of the file */
                   fileIn = new BufferedReader(new FileReader(fileParam));

                   /* read a line from the file and write the line 
                   to the browser page until the file is empty */
                   os.println("Writing from file " + fileParam);
                   os.println();

                   // read in lines and write to browser until end of stream is reached
                   while((lineIn = fileIn.readLine()) != null)
                   {
                       // check for empty line
                       if((lineIn.length()) > 0)
                       {
                           os.println(lineIn);
                       }
                       else
                       {
                          os.print(lineIn);
                       }
                    }

                    /* be sure to close the input file stream */
                   fileIn.close();
        }
        catch(Throwable e)
        {
           os.println(e.toString());
           PrintWriter pout = new PrintWriter(os);
           e.printStackTrace(pout);
           pout.flush();
           pout.close();
        }
    } // end of service() 
} // end of class FileToBrowserServlet 
