URL 我的URL=MyClass.class.getClassLoader().getResource(文件名);

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

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

这是我的 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;    
}//

我猜下面一行用于从 class 路径读取 属性 文件:

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

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

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

此外,我的代码现在有一个参数 clazz,它是 class 文件相对之后查找的 - 这样代码就更通用了,我假设是个好东西

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

我如下更改了我的代码,它运行良好

private String readPropVal(String propertyValue, String fileName) 抛出异常{

    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;    
    }//