[英]How to access java properties file
我有一個屬性文件。
#My properties file
config1=first_config
config2=second_config
config3=third_config
config4=fourth_config
我有一個在小型Java應用程序中加載屬性文件的類。 效果很好,特別是當我嘗試訪問此類方法中的每個屬性時。
public class LoadProperties {
public void loadProperties() {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("resources/config.properties");
prop.load(input);
} catch (Exception e) {
System.out.println(e);
}
}
}
我在另一個類的方法中調用該類的方法。
public class MyClass {
public void myMethod() {
LoadProperties lp = new LoadProperties();
lp.loadProperties();
/*..More code...*/
}
}
如何在MyClass
類的myMethod
方法中訪問屬性? 我嘗試輸入prop.getProperty("[property_name]")
,但這不起作用。
有任何想法嗎? 我假設這將是我訪問屬性的方式。 我可以將它們存儲在loadProperties
類的變量中並返回變量,但是我認為我將能夠像上面所說的那樣訪問它們。
您可以更改LoadProperties類以加載屬性,並添加方法以返回已加載的屬性。
public class LoadProperties {
Properties prop = new Properties();
public LoadProperties() {
try (FileInputStream fileInputStream = new FileInputStream("config.properties")){
prop.load(fileInputStream);
} catch (Exception e) {
System.out.println(e);
}
}
public Properties getProperties() {
return prop;
}
}
然后像這樣使用
public class MyClass {
public void myMethod() {
LoadProperties loadProperties = new LoadProperties();
System.out.println(loadProperties.getProperties().getProperty("config1"));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.