我正在尝试通过名为 ConnectionProvider
的类与数据库建立连接。
我在 Servlet
内部调用 ConnectionProvider.getConnection()
,它返回 Connection
引用。
但我在执行此类时遇到异常:
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)
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;
}
}
我无法使用 ServletContext.getResourceAsStream() 因为代码不是从 servlet 调用的。 我尝试将属性文件放入网络应用程序的公共(public)文件夹(根)内的每个位置,但这没有帮助。 我也不想在 Servlet 内硬编码连接代码,并希望一些帮助器类为我执行连接代码。
最佳答案
只需将其放入类路径中并从类路径加载即可。下面的示例假设您已将 db.properties
放到类路径的根目录中(例如包结构的根目录;例如在 Eclipse 中,这将直接位于 src
文件夹):
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) {}
}
另请参阅:
<小时/>与问题无关,忽略异常并仅打印其跟踪然后继续代码流的代码风格是一种非常糟糕的做法。您的代码将返回 null
连接,并且调用代码将因 NullPointerException
中断。您确实应该以明智的方式处理异常。在这种特殊情况下,只需抛出它或在另一个异常中重新抛出它。
也不需要每次在getConnection()
中加载驱动程序类。在应用程序的生命周期内一次就足够了。例如,您可以在 static
block 中执行此操作。不要忘记将任何捕获的异常重新抛出为 ExceptionInInitializerError
。
关于java - 如何在 Web 应用程序中使用 java io 访问文件(Glassfish 服务器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7222320/