• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to read a file inside a JSP

 
Neeraj Macker
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i need to read a small string from a txt file stored in the same folder as this JSP.when i run the below mentioned code from inside my JSP there is 404 error stating that it cannot find the file. what should be the url to be assigned to the File handle?




File f = new File("abc.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s = null;
s = br.readLine();
// do something with s ....
br.close();
fr.close();
 
Neeraj Macker
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok i got it. i fetched the real path by using request.getRealPath() and it works now.
 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Filenames should always be given with absolute paths. Check out ServletContext.getRealPath().

I'll use the opportunity to point out that it's not considered good design to have file I/O inside of JSP pages, just like one shouldn't have JDBC code inside JSPs.
[ August 12, 2005: Message edited by: Ulf Dittmer ]
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ulf Dittmer:
Filenames should always be given with absolute paths. Check out ServletContext.getRealPath().

I'll use the opportunity to point out that it's not considered good design to have file I/O inside of JSP pages, just like one shouldn't have JDBC code inside JSPs.

[ August 12, 2005: Message edited by: Ulf Dittmer ]


I agree.

In addition, I also don't recommend using getRealPath as it is not a portable solution. A better solution is to use context.getResource or contextGetResourceAsStream.
The getRealPath method will return null if the application is being run from a packed war file. Another is to use an absolute path and make it configurable with either a context init-param or a servlet-init param.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!