How to use Java property files?

后端 未结 17 1390
时光取名叫无心
时光取名叫无心 2020-11-22 11:13

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.

Questions:

  • Do I ne
17条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 11:55

    • 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().

提交回复
热议问题