Read a fweb resource in servlet

Hi all,

How can i read a file which is located inside the web application in servlet,.I have used getServletContext().getRealPath() but it is returning null when i deploy the application through war file,.

Please suggest me a work around here.

[262 byte] By [SecfGuya] at [2007-11-27 10:41:44]
# 1

Hi guys,

I think i am not clear in my question.Let me elaborate it.

I have a file inside my war file,,for ex: parallel to web-inf i have one folder ,,in that i have a file.I need to read it in my servlet.How can I achieve this.

servletContext().getRealPath("") is returning null in case of a war file.

Please suggest me any other way

Thanks

SecfGuya at 2007-7-28 19:14:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2

Use the classloader to load the file. Put the file or the subdirectory in your classes directory and then do something like:

InputStream is = getClass().getClassLoader().getResourceAsStream("subdir/file.txt");

This will look for the file as WEB-INF/classes/subdir/file.txt. If the file cannot be found the getResourceAsStream() method returns null.

gimbal2a at 2007-7-28 19:14:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3

Thanks a lot boss ,,It worked for now..

What if if i want to put a folder ,which is parallel to web-inf?how can i read that file?

Please suggest me,as i can not move that folder to classes/sub folder.

Thanks

SecfGuya at 2007-7-28 19:14:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4

well, you need to make the path to your web application configurable then. You can load a properties file in the way you know now, or you can put an init-parameter in your web.xml that contains the path to your WEB-INF directory so you can read that path and use it to create absolute paths to the files in the WEB-INF.

gimbal2a at 2007-7-28 19:14:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...