java4all@1986 java. Powered by Blogger.

How to read a text file in Servlets?

>> Monday, June 13, 2011

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 message.properties 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 message.properties which is going to be read through a servlets.


Hello World!

Where there is a will, there is a way

ReadTextFile.java
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 ReadTextFile extends HttpServlet {
  protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  
  response.setContentType("text/html");
  String filename = "/WEB-INF/message.properties";
  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>");
  
  while ((text = reader.readLine()) != null) {
  pw.println("

"+text+"


"); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }

0 comments:

Post a Comment

FaceBook Login

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

Total Pageviews

STATCOUNTER

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP