How do I read and output a text file from a Servlet?

Alex Chaffee

Try the following:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class MessageServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException
        // output an HTML page

        // load a configuration parameter (you must set this yourself)
        String root = getInitParameter("root");

        // print some html
        ServletOutputStream out = res.getOutputStream();
        out. println("<html>");
        out.println("<head><title>Message of the Day</title></head>");
        out.println("<body><h1>Today's Message:</h1>");

        // print the file
        InputStream in = null;
        try {
            in = new BufferedInputStream
                (new FileInputStream(root + "/message.txt") );
            int ch;
            while ((ch = in.read()) !=-1) {
        finally {
            if (in != null) in.close();  // very important

        // finish up
[Note: I have now successfully compiled and run the above example. You asked for working source, you got it :-)]

You may want to do more than just copy the file; look in the java.io package for classes that help you process a file, like StreamTokenizer.

Pay attention to the use of an InitParameter to provide a root on the file system. That way your servlet can be used on other servers without hardcoding a file path.

Also note the use of a finally block to close the file. This way, even if the reading throws an exception, the file will be closed. This is important on a server, since file descriptors are limited, and you don't want any leaks, since the server will be up for a very long time (hopefully!).

Whenever you access local resources, you have to consider security holes. For instance, if you make a file name based on a FORM parameter, you should validate it, to make sure if a hacker sends in, e.g., "/etc/passwd" as his user name, he won't actually get the system password file.

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.