我必须从其类路径访问我的.properties文件。目前我正在从资源文件夹直接访问它。但是现在我想要从班级道路上获得成功。
当前代码:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
try {
properties.load(new FileInputStream(
"src/resources/config.properties"));
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
rate.add(value);
}
}
}
文件路径为:src/resources/config.properties
为了部署代码,我们正在创建整个项目的war文件。
请建议我们如何从类路径中获取此文件。
答案 0 :(得分:3)
如果您的config.properties
文件驻留在您的java类的同一个包中,那么只需使用
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config.properties");
如果将属性文件放在任何包中,则还要使用包名称
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("com/your_package_name/config.properties");
所以竞争代码就像,
try {
Properties configProperties = new Properties();
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("resources/config.properties");
configProperties.load(inputStream);
}
catch(Exception e){
System.out.println("Could not load the file");
e.printStackTrace();
}
更新: 为了更好地理解,请参阅图像。
答案 1 :(得分:0)
您可以使用此
从类路径加载文件this.getClass().getClassLoader().getResourceAsStream("config.properties");
如果您要处理.properties
个文件,则应考虑使用ResourceBundle
答案 2 :(得分:0)
final Properties properties = new Properties();
try (final InputStream stream =
this.getClass().getResourceAsStream("somefile.properties")) {
properties.load(stream);
}