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

问题:

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


当前回答

在我看来,当我们可以非常简单地做到如下所示时,其他方法是不可取的:

@PropertySource("classpath:application.properties")
public class SomeClass{

    @Autowired
    private Environment env;

    public void readProperty() {
        env.getProperty("language");
    }

}

这很简单,但我认为这是最好的方法!! 享受

其他回答

例子:

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

在我看来,当我们可以非常简单地做到如下所示时,其他方法是不可取的:

@PropertySource("classpath:application.properties")
public class SomeClass{

    @Autowired
    private Environment env;

    public void readProperty() {
        env.getProperty("language");
    }

}

这很简单,但我认为这是最好的方法!! 享受

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

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

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

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