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 configuration.properties file from the /WEB-INF directory in our web application. The configuration.properties file is just a regular text file with the following contents.

app.appname=Servlet Examples
app.version=1.0
app.copyright=2021

Here is our ReadTextFileServlet servlet class.

package org.kodejava.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@WebServlet(name = "ReadTextFileServlet", urlPatterns = "/read-text-file")
public class ReadTextFileServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");

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

        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>");
            }
        }
    }
}

To access the servlet you can type http://localhost:8080/read-text-file in your browser URL address bar.

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

Wayan

5 Comments

  1. Thank you very much, I am new to the concept of servlets so I wanted to ask if this code could be used in case I want to read a JSON file and not a text file. And what should be changed in the code in order to do that.

    Thank you again

    Reply
    • Hi Azum, of course you can read a JSON file in servlet. JSON file is actually just a text file. You just need a library such as Gson, Jackson, JSON-Java, etc to process the JSON file. For example to convert it into Java object.

      Reply
    • Might be useful to drop the URL you input.
      Beware, the servet is named Read… but the URL to input is read… (lower case R)

      Reply
  2. I use similar code to read string values from a text file from a servlet. The servlet then uses .out to display the values in a jsp. Problem I have is that when the values change in the text file the servlet shows the old values after refreshing the page. The only way the servlet will display the new values is restarting the web app. Any idea? Is there a buffer I need to clear?

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.