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

问题:

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


当前回答

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

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

其他回答

你可以将一个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);
}

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

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

在顺序:

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

You can store the file anywhere you like. If you want to keep it in your jar file, you'll want to use Class.getResourceAsStream() or ClassLoader.getResourceAsStream() to access it. If it's on the file system it's slightly easier. Any extension is fine, although .properties is more common in my experience Load the file using Properties.load, passing in an InputStream or a StreamReader if you're using Java 6. (If you are using Java 6, I'd probably use UTF-8 and a Reader instead of the default ISO-8859-1 encoding for a stream.) Iterate through it as you'd iterate through a normal Hashtable (which Properties derives from), e.g. using keySet(). Alternatively, you can use the enumeration returned by propertyNames().

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