Servlet Read text file and Return contents Example

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

web.xml entry for Servlet

Servlet Program:

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

One thought on “Servlet Read text file and Return contents Example

Leave a Reply

Your email address will not be published. Required fields are marked *