How do I read text file in Servlet?

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

package org.kodejava.example.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

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

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}
}

The configuration.properties file is just a regular text file. Below is an example of the configuration we are going to read.

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

Wayan Saryada

I am a programmer, a runner, an open water diver and currently living in the island of Bali, Indonesia. If you need help on Java programming you can hire me on Fiverr.

Leave a Comment.