Properties files are a cool place to store your configuration details like database connection properties, error messages and other configurations for your program.
You can use properties file in your application using following utility class. This class basically loads your properties file on first attempt to access any property on further attempts to access any property it will return properties already loaded in memory and not attempt to read file again and again.
Static getProperty(String key)
method allows you to get property value by passing the key and static method Set<Object> getkeys()
returns a set of keys in the file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
package com.bharat.utils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;
public class PropertiesUtil
{
private static Properties props;
static
{
props = new Properties();
try
{
PropertiesUtil util = new PropertiesUtil();
props = util.getPropertiesFromClasspath("placeholder.properties");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
// private constructor
private PropertiesUtil()
{
}
public static String getProperty(String key)
{
return props.getProperty(key).trim();
}
public static Set getkeys()
{
return props.keySet();
}
/**
* loads properties file from classpath
*
* @param propFileName
* @return
* @throws IOException
*/
private Properties getPropertiesFromClasspath(String propFileName)
throws IOException
{
Properties props = new Properties();
InputStream inputStream =
this.getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream == null)
{
throw new FileNotFoundException("property file '" + propFileName
+ "' not found in the classpath");
}
props.load(inputStream);
return props;
}
}
|
You may put your properties file anywhere in project’s classpath.