我有一个配置值的键/值对列表,我想将其存储为Java属性文件,然后进行加载和遍历。
问题:
我是否需要将文件存储在与装入它们的类相同的包中,或者它应该放置在任何特定的位置? 文件是否需要以任何特定的扩展名结束,或者。txt OK? 如何在代码中加载文件 我如何遍历里面的值?
我有一个配置值的键/值对列表,我想将其存储为Java属性文件,然后进行加载和遍历。
问题:
我是否需要将文件存储在与装入它们的类相同的包中,或者它应该放置在任何特定的位置? 文件是否需要以任何特定的扩展名结束,或者。txt OK? 如何在代码中加载文件 我如何遍历里面的值?
当前回答
您可以通过以下方式加载属性文件:
InputStream is = new Test().getClass().getClassLoader().getResourceAsStream("app.properties");
Properties props = new Properties();
props.load(is);
然后你可以使用lambda表达式遍历映射,比如:
props.stringPropertyNames().forEach(key -> {
System.out.println("Key is :"+key + " and Value is :"+props.getProperty(key));
});
其他回答
您可以通过以下方式加载属性文件:
InputStream is = new Test().getClass().getClassLoader().getResourceAsStream("app.properties");
Properties props = new Properties();
props.load(is);
然后你可以使用lambda表达式遍历映射,比如:
props.stringPropertyNames().forEach(key -> {
System.out.println("Key is :"+key + " and Value is :"+props.getProperty(key));
});
例子:
Properties pro = new Properties();
FileInputStream in = new FileInputStream("D:/prop/prop.properties");
pro.load(in);
String temp1[];
String temp2[];
// getting values from property file
String username = pro.getProperty("usernamev3");//key value in prop file
String password = pro.getProperty("passwordv3");//eg. username="zub"
String delimiter = ","; //password="abc"
temp1=username.split(delimiter);
temp2=password.split(delimiter);
在顺序:
您可以将文件存储在几乎任何地方。 不需要延期。 Montecristo已经说明了如何加载这个。这应该没问题。 propertyNames()提供了一个用于迭代的枚举。
下面是遍历属性的另一种方法:
Enumeration eProps = properties.propertyNames();
while (eProps.hasMoreElements()) {
String key = (String) eProps.nextElement();
String value = properties.getProperty(key);
System.out.println(key + " => " + value);
}
在我看来,当我们可以非常简单地做到如下所示时,其他方法是不可取的:
@PropertySource("classpath:application.properties")
public class SomeClass{
@Autowired
private Environment env;
public void readProperty() {
env.getProperty("language");
}
}
这很简单,但我认为这是最好的方法!! 享受