Reading Text file in Servlet

Reading Text file in Servlet


Posted in : Java Posted on : June 21, 2011 at 4:21 PM Comments : [ 0 ]

In this section we will discuss how can a text file can be read in servlet.

Reading Text file in Servlet

In this section we will discuss how can a text file can be read in servlet.

In the example given below I created a text file "readingText". To read the text from the disk I have used the InputStream class and to read the file in servlet I used InputStreamReader class.

Example : TextFileReading.java

import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
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 TextFileReading extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
ServletContext cntxt = getServletContext();
String fName = "/WEB-INF/readingText";
InputStream ins = cntxt.getResourceAsStream(fName);
if(ins == null){
//pw.println("NOt Found");
res.setStatus(res.SC_NOT_FOUND);
}
else
{
BufferedReader br = new BufferedReader((new InputStreamReader(ins)));
String word;
while((word= br.readLine())!= null)
{
pw.println(word+"<br>");
}
}
}
}

web.xml

<web-app version="2.4">
<servlet>
<servlet-name>TextFileReading</servlet-name>
<servlet-class>TextFileReading</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TextFileReading</servlet-name>
<url-pattern>/TextFileReading</url-pattern>
</servlet-mapping>

</web-app>

Output : When you will run this example you will find the output as follows

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics