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.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;

@WebServlet(name = "ReadTextFileServlet", urlPatterns = "/read-text-file")
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>");

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

Maven dependencies


Maven Central


  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

    • 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.

    • 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)


Leave a Reply

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