How do I read text file in Servlet?

Category: javax.servlet, viewed: 21787 time(s).

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
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats