这是我在我的项目中读取.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
-target
-properties文件
-pom.xml
您可以查看我的项目结构:link
我的属性文件位于根项目下。 我在构建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)
答案 0 :(得分:1)
您需要从类路径中读取它。所以,假设它位于JAR的根目录(它将在src / main / resources / my.props的标准Maven项目布局下):
input = Configuration.class.getResourceAsStream(filename);