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 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?
Properties has become legacy. Preferences class is preferred to Properties.
Unlike properties which are String based key-value pairs, The
Preferences
class has several methods used to get and put primitive data in the Preferences data store. We can use only the following types of data:To load the the properties file, either you can provide absolute path Or use
getResourceAsStream()
if the properties file is present in your classpath.xml file:
Have a look at this article on internals of preferences store
Reading a properties file and loading its contents to
Properties
The following is the efficient way to iterate over a
Properties
There are many ways to create and read
properties
files:.properties
extension however you can choose your own.java.util
package =>Properties
,ListResourceBundle
,ResourceBundle
classes.Properties
orjava.lang.System
class.ResourceBundle
class:Properties
class:This load the properties file:
I use to put the .properties file in a directory where I have all the configuration files, I do not put it together with the class that accesses it, but there are no restrictions here.
For the name... I use .properties for verbosity sake, I don't think you should name it .properties if you don't want.
In Java 8 to get all your properties
By default, Java opens it in the working directory of your application (this behavior actually depends on the OS used). To load a file, do:
As such, any file extension can be used for property file. Additionally, the file can also be stored anywhere, as long as you can use a
FileInputStream
.On a related note if you use a modern framework, the framework may provide additionnal ways of opening a property file. For example, Spring provide a
ClassPathResource
to load a property file using a package name from inside a JAR file.As for iterating through the properties, once the properties are loaded they are stored in the
java.util.Properties
object, which offer thepropertyNames()
method.