[英]How to read properties file from web inf resource folder using classloader in java
Any suggestions to read properties file kept inside WEB-INF/resource using class loader. 有关使用类加载器读取保存在WEB-INF /资源中的属性文件的任何建议。 Something like :- 就像是 :-
String fileName = "/WEB-INF/resource/my.properties";
InputStream input =MyClass.class.getClassLoader().getResourceAsStream(fileName);
properties = new Properties();
properties.load(input);
(Note- I don't want to read using servletcontext) (注:我不想使用servletcontext阅读)
Find the error for above code:- 查找以上代码的错误:-
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)
use ServletContext to access your web resources not the class loader 使用ServletContext访问您的Web资源而不是类加载器
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getResourceAsStream(java.lang.String) http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getResourceAsStream(java.lang.String)
servletContext.getResourceAsString("/WEB-INF/resource/my.properties");
When you're using getResourceAsStream()
you're defaulting into the resources folder. 使用getResourceAsStream()
,默认情况下是进入资源文件夹。 Unless your WEB-INF
is in the resources folder, it's won't find it because it doesn't exist. 除非您的WEB-INF
位于resources文件夹中,否则将找不到它,因为它不存在。
If your source folder is src/main/com/mycompany/myapp/ and that's where web-inf is located, your path should be something like 如果您的源文件夹是src / main / com / mycompany / myapp /,并且这是web-inf所在的位置,则路径应类似于
String sourcePath = "../WEB-INF/resource/my.properties"
As you have to go back one folder (into the project root) and up into the WEB-INF folder. 因为您必须返回一个文件夹(进入项目根目录),然后进入WEB-INF文件夹。
I used this approach 我用这种方法
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.