java - 如何在 Web 应用程序中使用 java io 访问文件(Glassfish 服务器)

标签 java servlets properties glassfish

我正在尝试通过名为 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/

相关文章:

java - Jasypt - 如何使用 StrongPasswordEncryptor 作为 .properties 文件中的凭据

java - 我不明白为什么这会引发异常?

java - Weblogic session 转发中未维护Java Servlet HttpSession

properties - 未使用复合应用程序为此命名空间定义属性

java - 从 ServletContext 中移除监听器

java - 我什么时候将内存使用量加倍?

variables - 查找具有共同属性的变量

java - 处理 GET 请求 - Apache HttpClient 与 java.net.HttpURLConnection

java - 从图库中选择的图像不会在 ImageView 中设置

java - Java7 中的小程序在签署 jar 后无法工作