How to access a file using java io inside a web app(Glassfish server)
I am trying to make a connection with database from a class called ConnectionProvider
.
I call ConnectionProvider.getConnection()
inside Servlet
which return Connection
refrence.
But I get exception during execution of this class:
java.io.FileNotFoundException: db.properties (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.io.FileInputStream.<init>(FileInputStream.java:66)
code of ConnectionProvider:
public class ConnectionProvider {
static Properties prop;
static {
try{
prop= new Properties();
prop.load(new FileInputStream("db.properties"));
}catch(Exception e){
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection con=null;
try{
Class.forName(prop.getProperty("driver"));
con=DriverManager.getConnection(prop.getProperty("url"),prop.getProperty("user"),prop.getProperty("pass"));
}catch(Exception e){
e.printStackTrace();
}
return con;
}
}
I cannot use ServletContext.getResourceAsStream() bcause code is not called from servlet. I have tried to put property file in each and every location inside public folder (root) of web app but that doesn't help. I also donot want to hardcode the connectivity code inside Servlet and want some helper class to perform the connectivity code for开发者_JAVA百科 me.
Just put it in the classpath and load it from the classpath. The below example assumes that you've dropped db.properties
in the root of the classpath (e.g. the root of your package structure; in Eclipse for example that would be straight in the src
folder):
Properties properties = new Properties();
InputStream input = null;
try {
input = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
properties.load(input);
} finally {
if (input != null) try { input.close(); } catch (IOException ignore) {}
}
See also:
- getResourceAsStream() vs FileInputStream
Unrelated to the problem, your code style of ignoring the exception and just printing its trace and then continuing the code flow is a very bad practice. Your code would return a null
connection and the calling code would break with NullPointerException
. You should really handle the exception in a sensible manner. In this particular case, just throw it or rethrow it in another exception.
Loading the driver class everytime in the getConnection()
is also unnecessary. One time is enough during application's lifetime. You could do it in for example that static
block. Don't forget to rethrow any caught exception as ExceptionInInitializerError
.
精彩评论