我有一个配置值的键/值对列表,我想将其存储为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));
});
其他回答
有很多方法来创建和读取属性文件:
将文件存储在同一个包中。 推荐.properties扩展名,但你可以选择自己的。 使用java中的这些类。util package =>属性,ListResourceBundle, ResourceBundle类。 要读取属性,请使用properties或java.lang.System类的迭代器或枚举器或直接方法。
ResourceBundle类:
ResourceBundle rb = ResourceBundle.getBundle("prop"); // prop.properties
System.out.println(rb.getString("key"));
属性类:
Properties ps = new Properties();
ps.Load(new java.io.FileInputStream("my.properties"));
下面是遍历属性的另一种方法:
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");
}
}
这很简单,但我认为这是最好的方法!! 享受
我在去年写了关于这个属性框架的文章。 它将提供多种方式来加载属性,并具有强类型。
看看http://sourceforge.net/projects/jhpropertiestyp/
jhpropertiestype将为开发人员提供强类型的属性。 易于在现有项目中集成。 由属性类型的大型系列处理。 提供通过属性IO实现单行初始化属性的能力。 使开发人员能够创建自己的属性类型和属性io。 网页演示也可用,屏幕截图如上所示。 也有一个标准的web前端实现来管理属性,如果你选择使用它。
项目网页上有完整的文档、教程、javadoc、faq等。
您可以通过以下方式加载属性文件:
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));
});