【问题标题】:URL myURL=MyClass.class.getClassLoader().getResource(fileName);URL myURL=MyClass.class.getClassLoader().getResource(fileName);
【发布时间】:2015-06-13 14:44:42
【问题描述】:

如果属性文件在类路径中,则以下代码可以正常工作,但是当我将属性文件放在相关包中时,它根本不会读取它。

这是我的java代码:

private String readPropVal(String propertyValue, String fileName)throws Exception{

    String path="";

    URL myURL = CategoriesMethods.class.getClassLoader().getResource(fileName);
    InputStream in = myURL.openStream();
    ClassLoader classLoader = getClass().getClassLoader();
    Properties p = new Properties();

    p.load(new InputStreamReader(classLoader.getResourceAsStream(fileName), "UTF-8"));
    path = p.getProperty(propertyValue);

    return path;    
}//

我猜下面一行是用来从类路径中读取属性文件的:

URL myURL = CategoriesMethods.class.getClassLoader().getResource(fileName);

如何使用类路径以外的路径?

【问题讨论】:

  • 请加个标签说明这是什么语言,所以我们不需要依赖其他线索。
  • 请您更详细地解释一下这个问题。编辑您的帖子标题并添加特定于语言或框架的标签也将是建设性的,因为它使其他用户没有什么可做的。
  • 先发制人地猜测我们在这里谈论的是Java......

标签: java utf-8 properties-file


【解决方案1】:

对您的代码进行了一些修改以使其正常工作。看来您不需要使用classLoader,而是使用类本身。

另外,我的代码现在有一个参数 clazz,它是文件看起来相对的类 - 这样代码更通用,我认为这是一件好事。

private String readPropVal(String property, String fileName, Class<?> clazz) {

    String value = "";

    URL myURL = clazz.getResource(fileName);
    if (myURL == null) {
        fileName = clazz.getResource(".").toString() + fileName;
        throw new IllegalArgumentException(fileName + " does not exist.");
    }
    Properties p = new Properties();

    try {
        p.load(new InputStreamReader(myURL.openStream(), "UTF-8"));
    } catch (Exception e) {
        throw new IllegalStateException("problem reading file", e);
    }
    value = p.getProperty(property);

    if (value == null) {
        throw new IllegalArgumentException("Key \"" + property + "\" not found in " + myURL.toString());
    }

    return value;    
}

这个方法现在可以这样调用:

readPropVal("propertyName", "fileName.properties", AnyClassNextToTheFile.class)

fileName.properties 文件应该包含一行

propertyName = someValue

【讨论】:

  • 感谢您的回复,但很遗憾无法使用。它通过指示这一行来抛出 NPE p.load(new InputStreamReader(myURL.openStream(), "UTF-8"));
  • 改进了代码以更好地显示问题信息。
  • 即使那样它也不起作用。我重塑了我的代码并发布在上面。现在我的代码运行良好。
  • 衷心感谢 Mikk 给了我宝贵的时间
【解决方案2】:

我将我的代码更改如下,并且它运行良好

private String readPropVal(String propertyValue, String fileName) throws Exception{

    String path="";                             
        File propFile = new File(fileName);
    Properties properties = new Properties();
    properties.load(new InputStreamReader(new FileInputStream(propFile),"UTF-8"));
        path = properties.getProperty(propertyValue);          
        return path;    
    }//     

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-24
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多