skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Wednesday, October 10, 2012

How to read the content of a flat file from JSP

Posted by Raju Gupta at 11:29 AM – 0 comments
 
As like in Java code we canĂ¢€™t hardcode the filenames in JSP. Because the application path differ from server to server and it needs to be generated dynamically. So getting the application path at run time is the key point in reading a flat file from JSP. Once we get the application path the remaining part is similar to Java code.
The method that is used to get the application path is getRealPath. This is available in the interface ServletContext. We can access this method in JSP using implicit object, Application.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
<title>Question & Answer Page</title>
</head>
<body>

<h2><center>Welcome to Questionnaire Forum....!</center></h2>
<br/><br/>



<%@ page import = "java.lang.*,java.io.*,java.util.*" %>
<%


// variables for connecting to the flat file data source
// Note: this is set up to look in the same directory as the jsp file.


String fileName = "question_answer.txt";
BufferedReader br = null;
FileReader fr;

String inputPath = application.getRealPath("/") + File.separatorChar;

try {

// open a bufferedreader to read the file
// get the current path of the jsp under the application server.
// 'application' is a freebie from the parent servlet.



      fr = new FileReader (new File(inputPath + fileName));
      br = new BufferedReader (fr);
      String line = br.readLine();

      while (line != null) {
 
 out.println(line);
%>

<br/>

<%
 line = br.readLine();
    }
 
 br.close();



   } 

catch (Exception e) {


}


%>


</body>
</html>

Labels: Java File Example , JSP Example

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger