【问题标题】:How to load properties file in a JSF application? [duplicate]如何在 JSF 应用程序中加载属性文件? [复制]
【发布时间】:2016-01-31 20:03:53
【问题描述】:

我正在尝试将properties 文件加载到我正在开发的JSF 应用程序中,但我无法引用该文件。

package com.nivis.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropHandler {

    String result = "";
    InputStream inputStream;

    public void loadProp() {

        try {

            inputStream = this.getClass().getResourceAsStream("prop.properties");

            if (inputStream == null) {
                System.err.println("===== Did not load =====");
            } else {
                System.err.println("===== Loaded =====");
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        PropHandler ph = new PropHandler();
        ph.loadProp();
    }
}

该文件位于同一个包中,并且在我搜索此文件时发现的不同示例中,应该可以。我还尝试将文件放在应用程序的每个可能的位置,并尽我所知引用它,但它不起作用。

(只有一些我测试过的文件夹)

我做错了什么?

最好将它放在用于msg.properties 文件的同一文件夹中。

【问题讨论】:

  • 你考虑过stackoverflow.com/questions/2161054/…中的答案
  • 你试过getClass().getResourceAsStream("com/nivis/prop.properties");吗?
  • @Zhedar:是的,它不起作用。
  • 现在我尝试使用/com/nivis/prop.properties,它确实有效。奇怪,我以为我已经尝试过那个特定的组合...看看我是否可以使用与 msg.properties 文件相同的文件夹来让它工作。
  • 在 JSF 中使用 ExternalContext#getResourceAsStream(String path) 并更好地将属性文件移动到 WEB-INF,因为它是一个 Web 资源。

标签: jsf jsf-2.2 properties-file


【解决方案1】:

正如this answer 所阐述的那样,com/nivis/prop.properties 应该是引用嵌套在资源文件夹中的文件的正确方法。
但是因为您没有使用ClassLoader classloader = Thread.currentThread().getContextClassLoader(); 来定位Classloader您必须使用以“/”开头的绝对路径,从而导致/com/nivis/prop.properties

【讨论】:

  • 非常感谢您抽出宝贵时间帮助我!
【解决方案2】:
try something like this

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("prop.properties");

【讨论】:

  • 恐怕没用。
  • 您是否尝试了以下链接中指定的所有 3 个选项@tom stackoverflow.com/questions/2161054/…
  • 我确实尝试将文件放在大多数文件夹中,包括 web-inf。虽然我不确定我尝试了哪些路径组合。无论如何,它现在可以使用/com/nivis/prop.properties。谢谢
  • 请务必将其标记为已回答,以便帮助其他有类似问题的人
  • 将属性文件放入WEB-INF 只是在健全的JSF 应用程序中执行InputStream inputStream = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/WEB-INF/prop.properties"); 的问题。
猜你喜欢
  • 2013-06-18
  • 2011-03-10
  • 2018-06-30
  • 1970-01-01
  • 1970-01-01
  • 2012-06-10
  • 1970-01-01
  • 2016-07-17
  • 1970-01-01
相关资源
最近更新 更多