如何访问java属性文件
我有一个属性文件如何访问java属性文件,java,class,properties,getproperties,Java,Class,Properties,Getproperties,我有一个属性文件 #My properties file config1=first_config config2=second_config config3=third_config config4=fourth_config 我有一个类,它在一个小型Java应用程序中加载属性文件。它工作得很好,特别是当我尝试访问此类方法中的每个属性时 public class LoadProperties { public void loadProperties() { Properties
#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\u 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"));
}
}
您可以更改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"));
}
}
与问题代码相同,您不关闭
文件输入流
。完成后必须关闭流,最好使用。我知道,我很懒,只回答原始问题。还应执行适当的异常处理,而不是使用System.out.PrintLn。对于问题代码,您不需要关闭文件InputStream
。完成后必须关闭流,最好使用。我知道,我很懒,只回答原始问题。还应执行适当的异常处理,而不是使用System.out.println