reading a properties file from jsp
i have a properties file and a jsp file in same package . i write code for reading the properties file in jsp witin scriptlet. But i am getting the filenotfound exception. I executed the same program using java class it is executing properly. What is the problem.
Thanks in advance
<%@ page import="java.io.FileInputStream"%>
<%@ page import="java.io.FileNotFoundException"%>
<%@ page import="java.util.Properties"%>
<%Properties properties = new Properties();
try{
FileInputStream fin=new FileInputStream("simple.properties");
properties.load(fin);
System.out.println(properties.getProperty("mainclass"));
}catch(FileNotFoundException fe){
fe.printStackTrace();
System.out.println("the specified file cannot found");
}catch(Exception e){}
%>
> i have a properties file and a jsp file in same package .
This sounds weird, as the server usually takes care of package information for JSPs when translating them into servlets.
What about putting your file in your classes structure instead, and specify fully qualified name when trying to load ?
JSPs are translated to java, and that java and the coresponding class files are placed in work directories by the server, not under the WEB-INF/classes directory.
So it's all about getting to the properties file.
I'd suggest the cleanest way would be to use the ServletContext getResourceAsStream and place the properties file somewhere under the WEB-INF directory. Something like this:
<%! private static Properties myProperties; %>
<% if(myProperties == null) {
Properties newProps = new Properties();
InputStream is = getServletContext().getResourceAsStream("WEB-INF/my.properties");
newProps.load(is);
is.close();
myProperties = newProps;
}
%>
The use of a temporary variable is important for thread safety. You'll propably need to add a try-catch for IOException.
> please its urgent.
it's not. I've never had a need to do that, and I seriously doubt anyone else here has.
We certainly have never had a need to do it in the extraordinarilly ugly way you're trying to use.
JSTL can read resourcebundles for i18n purposes. Use that instead.