繁体   English   中英

如何使用Java中的类加载器从Web Inf资源文件夹中读取属性文件

[英]How to read properties file from web inf resource folder using classloader in java

有关使用类加载器读取保存在WEB-INF /资源中的属性文件的任何建议。 就像是 :-

String fileName = "/WEB-INF/resource/my.properties";
InputStream input =MyClass.class.getClassLoader().getResourceAsStream(fileName);
properties = new Properties(); 
properties.load(input);

(注:我不想使用servletcontext阅读)

查找以上代码的错误:-

java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Unknown Source)
at java.util.Properties.load0(Unknown Source)
at java.util.Properties.load(Unknown Source)

使用ServletContext访问您的Web资源而不是类加载器

http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getResourceAsStream(java.lang.String)

servletContext.getResourceAsString("/WEB-INF/resource/my.properties");

使用getResourceAsStream() ,默认情况下是进入资源文件夹。 除非您的WEB-INF位于resources文件夹中,否则将找不到它,因为它不存在。

如果您的源文件夹是src / main / com / mycompany / myapp /,并且这是web-inf所在的位置,则路径应类似于

String sourcePath = "../WEB-INF/resource/my.properties"

因为您必须返回一个文件夹(进入项目根目录),然后进入WEB-INF文件夹。

我用这种方法

public class HibernateConfig {

    public static final Properties HIBERNATE_PROPERTIES = readProperties();

    private static final String HIBERNATE_PROPERTIES_RESOURCE = "hibernate.properties";


    private static Properties readProperties() {
        try (BufferedInputStream is = new BufferedInputStream(ClassLoader.getSystemResourceAsStream(HIBERNATE_PROPERTIES_RESOURCE))) {
            Properties properties = new Properties();
            properties.load(is);
            return properties;
        } catch (IOException e) {
            throw new RuntimeException("Failed to read properties from scr/properties.");
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM