How to read text file in Servlets

In this section, you will learn how to read text file in servlets.

How to read text file in Servlets


This section illustrates you how to read text file in servlets.

In this example we will use the input stream to read the text from the disk file. The InputStreamReader class is used to read the file in servlets program. You can use this code in your application to read some information from a file.

Create a file in the /WEB-INF/ directory. We will read the content of this file and display in the browser. 

Get the file InputStream using ServletContext.getResourceAsStream() method. If input stream is not equal to null, create the object of InputStreamReader and pass it to the BufferedReader. A variable text is defined of String type. Read the file line by line using the while loop  ((text = reader.readLine()) != null). Then the writer.println(text) is used to display the content of the file

Here is the file which is going to be read through a servlets.

Hello World!

Where there is a will, there is a way.

Here is the code of

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 ReadTextFile extends HttpServlet {
  protected void doGet(HttpServletRequest request,
  HttpServletResponse response) throws ServletException, IOException {
  String filename = "/WEB-INF/";
  ServletContext context = getServletContext();
  InputStream inp = context.getResourceAsStream(filename);
  if (inp != null) {
  InputStreamReader isr = new InputStreamReader(inp);
  BufferedReader reader = new BufferedReader(isr);
  PrintWriter pw = response.getWriter();
  pw.println("<html><head><title>Read Text File</title></head>
<body bgcolor='cyan'></body></html>");
  String text = "";
  while ((text = reader.readLine()) != null) {
  protected void doPost(HttpServletRequest request,
  HttpServletResponse response) throws ServletException, IOException {

This will read the file and following output will be displayed on your browser

Download Source Code

Share on Google+Share on Google+

How to read text file in Servlets

Posted on: July 19, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: How to read text file in Servlets   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
Yogesh Krishnani
May 30, 2013

I have one doubt. why do we sent data using printwriter in html form.. ?? can't we send normal strings..??