Servlet Read text file and Return contents Example


Sometimes, the client may ask the Servlet to send the file contents of a file existing on the server. It is not file download. Here, the Servlet reads manually line-by-line and send each line separately to client. Read Servlet Read text file.
Example on Servlet Read text file

Client HTML Program: TextFileReadAndSend.html

Getting File contents from the Server

Enter File Name

web.xml entry for Servlet TextFileReadAndSend.java


  snrao1
  TextFileReadAndSend



  snrao1
  /TFRAS

Servlet Program: TextFileReadAndSend.java

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.*;

public class TextFileReadAndSend extends HttpServlet   
{
  public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException  
  {
    res.setContentType("text/html");
    PrintWriter pw = res.getWriter();

    String name = req.getParameter("filename");

    BufferedReader br = new BufferedReader(new FileReader("c:/"+name));
		
    String str;
    while( (str = br.readLine()) != null )
    {
     pw.println(str + "
"); } br.close(); pw.close(); } }

BufferedReader br = new BufferedReader(new FileReader("c:/"+name));

The file asked by the user is assumed to exist in C drive. This also can be taken from client (security may prevent this). Instead, the classpath of the file can be placed in <context-param> and read into the Servlet.

For performance reasons, BufferedReader readLine() method is used instead of FileReader read() method.

Reading and sending HTML file contents is very different from text file and is explained in Read HTML File Contents Example.

Client HTML file with user entry of File name

Servlet Read text file

Output screen with File contents sent by Servlet

Servlet Read text file

1 thought on “Servlet Read text file and Return contents Example”

  1. please help me to write content from java servelt to text file on pc
    i am facing an accesse denied 500 issue

Leave a Comment

Your email address will not be published.