我有一个配置值的键/值对列表,我想将其存储为Java属性文件,然后进行加载和遍历。

问题:

我是否需要将文件存储在与装入它们的类相同的包中,或者它应该放置在任何特定的位置? 文件是否需要以任何特定的扩展名结束,或者。txt OK? 如何在代码中加载文件 我如何遍历里面的值?


当前回答

你可以将一个InputStream传递给属性,所以你的文件几乎可以在任何地方,并被称为任何东西。

Properties properties = new Properties();
try {
  properties.load(new FileInputStream("path/filename"));
} catch (IOException e) {
  ...
}

迭代:

for(String key : properties.stringPropertyNames()) {
  String value = properties.getProperty(key);
  System.out.println(key + " => " + value);
}

其他回答

有很多方法来创建和读取属性文件:

将文件存储在同一个包中。 推荐.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"));

如果将属性文件放在与类Foo相同的包中,就可以轻松地加载它

new Properties().load(Foo.class.getResourceAsStream("file.properties"))

鉴于Properties扩展了哈希表,您可以以与在哈希表中相同的方式遍历值。

如果你使用*。你可以获得编辑器支持,例如Eclipse有一个属性文件编辑器。

在Java 8中获取所有属性

public static Map<String, String> readPropertiesFile(String location) throws Exception {

    Map<String, String> properties = new HashMap<>();

    Properties props = new Properties();
    props.load(new FileInputStream(new File(location)));

    props.forEach((key, value) -> {
        properties.put(key.toString(), value.toString());
    });

    return properties;
}

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

例子:

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);