我有一个配置值的键/值对列表,我想将其存储为Java属性文件,然后进行加载和遍历。
问题:
我是否需要将文件存储在与装入它们的类相同的包中,或者它应该放置在任何特定的位置? 文件是否需要以任何特定的扩展名结束,或者。txt OK? 如何在代码中加载文件 我如何遍历里面的值?
我有一个配置值的键/值对列表,我想将其存储为Java属性文件,然后进行加载和遍历。
问题:
我是否需要将文件存储在与装入它们的类相同的包中,或者它应该放置在任何特定的位置? 文件是否需要以任何特定的扩展名结束,或者。txt OK? 如何在代码中加载文件 我如何遍历里面的值?
当前回答
在我看来,当我们可以非常简单地做到如下所示时,其他方法是不可取的:
@PropertySource("classpath:application.properties")
public class SomeClass{
@Autowired
private Environment env;
public void readProperty() {
env.getProperty("language");
}
}
这很简单,但我认为这是最好的方法!! 享受
其他回答
读取属性文件并将其内容加载到properties
String filename = "sample.properties";
Properties properties = new Properties();
input = this.getClass().getClassLoader().getResourceAsStream(filename);
properties.load(input);
下面是遍历Properties的有效方法
for (Entry<Object, Object> entry : properties.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
加载属性文件:
Properties prop = new Properties();
InputStream stream = ...; //the stream to the file
try {
prop.load(stream);
} finally {
stream.close();
}
我把.properties文件放在一个存放所有配置文件的目录中,我没有把它与访问它的类放在一起,但这里没有限制。
对于这个名字…为了冗长起见,我使用。properties,如果你不想的话,我认为你不应该把它命名为。properties。
有很多方法来创建和读取属性文件:
将文件存储在同一个包中。 推荐.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"));
在我看来,当我们可以非常简单地做到如下所示时,其他方法是不可取的:
@PropertySource("classpath:application.properties")
public class SomeClass{
@Autowired
private Environment env;
public void readProperty() {
env.getProperty("language");
}
}
这很简单,但我认为这是最好的方法!! 享受
1)在类路径中有你的属性文件是很好的,但你可以把它放在项目的任何地方。
下面是如何从类路径加载属性文件并读取所有属性。
Properties prop = new Properties();
InputStream input = null;
try {
String filename = "path to property file";
input = getClass().getClassLoader().getResourceAsStream(filename);
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
return;
}
prop.load(input);
Enumeration<?> e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = prop.getProperty(key);
System.out.println("Key : " + key + ", Value : " + value);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2)属性文件的扩展名为.properties