【问题标题】:Not able to load properties file in Dynamic web project in Eclipse for Java无法在 Eclipse for Java 的动态 Web 项目中加载属性文件
【发布时间】:2016-02-09 08:08:23
【问题描述】:

我已将属性文件放在我的动态 Web 项目的 Webcontent 文件夹中。但是,它会抛出空指针异常。这是我的代码。

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream input = classLoader.getResourceAsStream("Resources.properties");
    System.out.println(input);
    Properties properties = new Properties();       
    properties.load(input);     
    System.out.println("MySQL Driver :"+properties.getProperty("mysqlDriver"));

我的属性文件包括

mysqlDriver = com.mysql.jdbc.Driver

我在 InputStream 处遇到错误 input = classLoader.getResourceAsStream("Resources.properties");

错误是

Feb 09, 2016 2:58:50 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [DatabaseAccess] in context with path  [/iNTU] threw exception
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Unknown Source)
at java.util.Properties.load0(Unknown Source)

【问题讨论】:

    标签: java eclipse


    【解决方案1】:

    将“Resources.properties”文件放在动态 Web 项目的“src”文件夹中(通过右键单击 Jara Resources/src > new > general > File 来创建它,命名为“MyResources.properties”)。 然后应该将读取属性文件的代码更新为:

    InputStream input = classLoader.getResourceAsStream("/Resources.properties");
    //If you use a subfolder of src, please update accordingly.
    

    这样,Eclipse 将知道如何将编译后的文件与属性文件一起部署到战争的 WEB-INF/类中。

    【讨论】:

    • 欧内斯特,我没有 src 或 src/main/resources 路径。我有 Java Resources:src,我只能在其中添加包、文件夹或类。
    • 是的,就是这个。将文件放在您的 java 源包所在的文件夹中。
    • 但是我怎样才能把属性文件放在那里呢?你的意思是和课程一起?
    • 你的项目的布局是什么?您有 sevlet 或其他 Java 源文件吗?你是怎么编译的?如果源文件夹中有非 java 文件,编译器会将其复制到目标目录。但是您的构建系统会影响这一点。如果您使用的是 Eclipse 动态 Web 项目,请将文件放在“src”下(假设这是您的 java 源目录)。如果您使用 maven 构建,请将 Resources.properties 文件放在 src/main/resources 中。如果您使用的是 ant,则将文件放在顶级 src 文件夹中。
    • 我在 Eclipse 中使用动态 web 项目。在 src 中,我只能添加一个向导。属性文件,我不能
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 2015-10-21
    相关资源
    最近更新 更多