【问题标题】:Properties file not found - how to locate it as resource?找不到属性文件 - 如何将其定位为资源?
【发布时间】:2013-04-09 06:20:05
【问题描述】:

我在某个位置有一个属性文件(来自 netbeans 项目资源管理器)

-MyTest
    +Web Pages
    +Source Packages
    -Test Packages
        -<default package>
            +Env.properties     <---- Here it is
        +com.mycomp.gts.test
        +com.mycomp.gts.logintest
        .....
        ....

现在当我尝试使用代码查找此文件时

InputStream propertiesInputStream = getClass().getResourceAsStream("Env.properties");
ENV.load(propertiesInputStream);

它的投掷java.lang.NullPointerException

【问题讨论】:

标签: java


【解决方案1】:

您不能使用类作为引用来加载资源,因为资源路径不是相对于类。改用类加载器:

InputStream propertiesInputStream = getClass().getClassLoader()
        .getResourceAsStream("Env.properties");
ENV.load(propertiesInputStream);

或者,您可以使用当前线程的上下文类加载器:

InputStream propertiesInputStream = Thread.currentThread()
    .getContextClassLoader().getResourceAsStream("Env.properties");
ENV.load(propertiesInputStream);

【讨论】:

    【解决方案2】:
    String basePath = PropertiesUtil.class.getResource("/").getPath();
    InputStream in = new FileInputStream(basePath + "Env.properties");
    pros.load(in);
    

    祝你好运:)

    【讨论】:

    • 指任何类都可以。
    • 构建失败:找不到符号类 PropertiesUtil
    • 将PropertiesUtil替换为classpath中的任意类,我的解决方案绝对OK。
    • 在运行时 basePath 是 /build/web/WEB-INF/classes/ 但我的属性文件在 /build/test/classes/
    【解决方案3】:

    尝试获取绝对路径:

    String absolute = getClass().getProtectionDomain().getCodeSource().getLocation().toExternalForm();
    

    您可以打印出字符串 absolute 并尝试将其子串到您的属性文件的路径中。

    【讨论】:

      【解决方案4】:

      以下代码读取存储在 Maven 项目的资源文件夹中的属性文件。

      InputStream inputStream = YourClass.class.getResourceAsStream("/filename.properties");
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
          
      Properties properties = new Properties();
      properties.load(reader);
        
      } catch (IOException ioException) {
          ioException.printStackTrace();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-22
        • 1970-01-01
        • 2015-10-01
        • 2011-06-22
        • 1970-01-01
        • 1970-01-01
        • 2014-04-22
        • 2013-11-28
        相关资源
        最近更新 更多