[英]Properties file not found in jar
这是我在我的项目中读取 .properties 文件的代码。
public class Configuration {
private static JSONObject readConfigFile(File filename) throws JSONException {
JSONObject configProperties = new JSONObject();
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(filename);
// load a properties file
prop.load(input);
// get the property value and print it out
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return configProperties;
}
public static JSONObject loadConfigurationDetails(String configFilePath) throws JSONException {
JSONObject configurationDetails = new JSONObject();
File configFile = new File(configFilePath);
if(configFile.exists()){
configurationDetails = readConfigFile(configFile);
}else{
System.out.println("configuration.properties file not found");
System.exit(0);
}
return configurationDetails;
}
public static JSONObject loadConfigurationDetails() throws JSONException {
String configFilePath = "configuration.properties";
JSONObject loadConfigurationDetails = loadConfigurationDetails(configFilePath);
return loadConfigurationDetails;
}
}
以下是我的项目结构
项目名
-src
-目标
- 属性文件
-pom.xml
您可以查看我的项目结构: 链接
我的属性文件在根项目下。 当我构建 jar 文件并运行它时,我无法读取此文件。 我正在获取找不到属性文件的文件。
在我的 Main 方法中,我按如下方式调用我的方法:
JSONObject loadConfigurationDetails = Configuration.loadConfigurationDetails();
修改后的代码和错误
public class Configuration {
public static JSONObject loadConfigurationDetails() throws JSONException {
Properties prop = new Properties();
String filePath = "";
JSONObject configProperties = new JSONObject();
try {
InputStream inputStream =
Configuration.class.getClassLoader().getResourceAsStream("configuration.properties");
prop.load(inputStream);
configProperties.put("URL",prop.getProperty("URL",""));
} catch (IOException e) {
e.printStackTrace();
}
return configProperties;
}
}
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
at com.demo.main.Configuration.loadConfigurationDetails(Configuration.java:33)
at com.demo.main.Run.main(Run.java:30)
您需要从类路径中读取它。 因此,假设它位于 JAR 的根目录中(它将位于 src/main/resources/my.props 的标准 Maven 项目布局下):
input = Configuration.class.getResourceAsStream(filename);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.