why i cant read simple text file in jsp
Hello all
i have this simple function that will read me line by line from giving text file
that is in the under webapps dir of my tomcat
public String getConst(String category,String param){
String filename ="\\conf.txt";
try{
java.io.BufferedReader in =new java.io.BufferedReader(new java.io.FileReader( filename) );
String str;
while ((str = in.readLine()) !=null){
str+=str;
}
return str;
}catch(java.io.IOException e){
return"file not found";
}
}
and stillim geting file not found all the time why is that?
[1192 byte] By [
Meirya] at [2007-10-3 2:31:08]

I think what you are needing is that helpful method in the ServletContext class: getRealPath().
Or even better: getResourceAsStream.
Both of these methods take a website relative path, and turn it into a real location on the disk. One returns a string being the file name, the other an actual input stream to the file.
The getResourceAsStream is more reliable, becuase getRealPath() will fail if the app is bundled in a WAR.
Also, your String reading method is inefficient - you should be using a StringBuffer to build a String like that.
Plus the fact that you overwrite your str variable every time you read a line - the result would be null.
This code needs to be in a servlet, to get the ServletContext.
ServletContext application = this.getServletConfig().getServletContext();
BufferedReader in = new BufferedReader(new InputStreamReader(application.getResourceAsStream(filename));
String result = readInput(in);
//...........
// And a helper method that reads a string more efficiently than you did.
public String readInput(BufferedReader in){
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter();
String str;
while ((str = in.readLine()) != null) {
out.println(str);
}
return sw.getBuffer().toString();
}
Cheers,
evnafets