[英]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資源而不是類加載器
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.