How do I read text file in Servlet?

This example show you how to read a text file in a servlet. Using the ServletContext.getResourceAsStream() method will enable you to read a file whether the web application is deployed in an exploded format or in a war file archive.

The following servlet read the file from the /WEB-INF directory in our web application. The file is just a regular text file with the following contents.

app.appname=Servlet Examples

Here is our ReadTextFileServlet servlet class.

package org.kodejava.example.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ReadTextFileServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {


        // We are going to read a file called This
        // file is placed under the WEB-INF directory.
        String filename = "/WEB-INF/";

        ServletContext context = getServletContext();

        // First get the file InputStream using ServletContext.getResourceAsStream()
        // method.
        InputStream is = context.getResourceAsStream(filename);
        if (is != null) {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader reader = new BufferedReader(isr);
            PrintWriter writer = response.getWriter();
            String text;

            // We read the file line by line and later will be displayed on the
            // browser page.
            while ((text = reader.readLine()) != null) {
                writer.println(text + "</br>");

After creating the servlet class we need to register our servlet and create a servlet-mapping in the web.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    <display-name>Servlet Examples</display-name>

To access the servlet you can type http://localhost:8080/readTextFileServlet in your browser URL textbox..

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.

Leave a Reply