Java URL myURL=MyClass.class.getClassLoader().getResource(文件名);

Java URL myURL=MyClass.class.getClassLoader().getResource(文件名);,java,utf-8,properties-file,Java,Utf 8,Properties File,如果属性文件位于类内路径中,那么下面的代码可以正常工作,但当我将属性文件放置在相关包中时,它根本不会读取它 以下是我的java代码: private String readPropVal(String propertyValue, String fileName)throws Exception{ String path=""; URL myURL = CategoriesMethods.class.getClassLoader().getResource(fileName)

如果属性文件位于类内路径中,那么下面的代码可以正常工作,但当我将属性文件放置在相关包中时,它根本不会读取它

以下是我的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);

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

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

另外,我的代码现在有一个参数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;    
}
其中fileName.properties文件应包含一行,如

propertyName = someValue

我改变了我的代码如下,它的工作完美

私有字符串readPropVal(字符串属性值,字符串文件名)引发异常{

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

请添加一个标记来指明这是哪种语言,这样我们就不需要依赖其他线索。请您更详细地解释一下这个问题。编辑您的文章标题并添加特定于语言或框架的标记也将是有建设性的,因为它给其他用户提供的信息很少。先发制人地猜测我们在这里谈论的是Java…这是为您的回复添加了nks,但不幸的是没有工作。它通过指示这一行p.load来抛出NPE(新的InputStreamReader(myURL.openStream(),“UTF-8”));改进了代码,以便在问题上显示更好的消息。即使这样,它也不起作用。我重新修改了代码并在上面发布。现在我的代码工作正常。衷心感谢Mikk给我宝贵的时间
    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;    
    }//