如何使用Java属性文件? [英] How to use Java property files?

查看:103
本文介绍了如何使用Java属性文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个配置值的键/值对列表,我希望将其存储为Java属性文件,然后加载并迭代。

I have a list of key/value pairs of configuration values I want to store as Java property files, and later load and iterate through.

问题:


  • 我是否需要将文件存储在与将加载它们的类相同的包中,或者是否存在应放置它的任何特定位置?

  • 文件是否需要以任何特定扩展名结尾,或 .txt 确定?

  • 如何在代码中加载文件

  • 如何迭代里面的值?

  • Do I need to store the file in the same package as the class which will load them, or is there any specific location where it should be placed?
  • Does the file need to end in any specific extension or is .txt OK?
  • How can I load the file in the code
  • And how can I iterate through the values inside?

推荐答案

你可以将一个InputStream传递给Property,所​​以你的文件几乎可以在任何地方,并且可以调用任何东西。

You can pass an InputStream to the Property, so your file can pretty much be anywhere, and called anything.

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属性文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆