Showing posts with label read text file. Show all posts
Showing posts with label read text file. Show all posts

Tuesday, September 9, 2014

How to 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 com.javacoderanch.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