This time, I will introduce how to read Java Property file.
A Property file is a file that stores data with a pair of keys and values. It is the same as the Windows ini file. It is used as a file to save the setting values of the program. If you describe it in the Property file, you can change the behavior of the program without compiling, so it is better to set a value that may change later. For example, user ID and password.
The description format is described by connecting the key and value with "= (equal)". Specifically, it looks like the following.
Key=value
In addition, the comment is displayed after the "# (sharp)" written at the beginning of the line.
#This line is a comment.
Key 1=value
Key 2=value#
Key 3#=value
In this case, the value corresponding to "Key 2" is "Value #". Also, the value corresponding to "Key 3 #" is "Value".
Use java.util.Properties to load the Property file. I think it is faster to see the actual program, so I will describe a concrete example.
public class PropertyUtil {
private static final String INIT_FILE_PATH = "resourse/common.properties";
private static final Properties properties;
private PropertyUtil() throws Exception {
}
static {
properties = new Properties();
try {
properties.load(Files.newBufferedReader(Paths.get(INIT_FILE_PATH), StandardCharsets.UTF_8));
} catch (IOException e) {
//File reading failed
System.out.println(String.format("Failed to read the file. file name:%s", INIT_FILE_PATH));
}
}
/**
*Get property value
*
* @param key key
* @return value
*/
public static String getProperty(final String key) {
return getProperty(key, "");
}
/**
*Get property value
*
* @param key key
* @param defaultValue Default value
* @Default value if return key does not exist
*Value, if present
*/
public static String getProperty(final String key, final String defaultValue) {
return properties.getProperty(key, defaultValue);
}
Use the Properties load function to load the Property file. load receives Reader as an argument, so use Reader that has read the Property file. The value of the loaded Property file can be obtained by specifying the key and using the getProperty function. Let's write a usage example.
common.properties
test=Test value
public static void main(String[] args) {
System.out.println(PropertyUtil.getProperty("test")); //⇒ Test value
}
If you specify the key like this, you can get the corresponding value.
that's all.
Recommended Posts