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

问题:

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


当前回答

读取属性文件并将其内容加载到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());
    }

其他回答

下面是遍历属性的另一种方法:

Enumeration eProps = properties.propertyNames();
while (eProps.hasMoreElements()) { 
    String key = (String) eProps.nextElement(); 
    String value = properties.getProperty(key); 
    System.out.println(key + " => " + value); 
}

在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;
}

在顺序:

您可以将文件存储在几乎任何地方。 不需要延期。 Montecristo已经说明了如何加载这个。这应该没问题。 propertyNames()提供了一个用于迭代的枚举。

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

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

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

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

默认情况下,Java在应用程序的工作目录中打开它(这种行为实际上取决于所使用的操作系统)。要加载一个文件,请执行:

Properties props = new java.util.Properties();
FileInputStream fis new FileInputStream("myfile.txt");
props.load(fis)

因此,任何文件扩展名都可以用于属性文件。此外,文件也可以存储在任何地方,只要您可以使用FileInputStream。

需要注意的是,如果使用现代框架,该框架可能提供打开属性文件的其他方法。例如,Spring提供了一个ClassPathResource来从JAR文件中使用包名加载属性文件。

至于遍历属性,一旦加载了属性,它们就存储在java.util.Properties对象中,该对象提供了propertyNames()方法。