Reading Properties file in Java
Based on your exception, the InputStream
is null, this means the class loader is not finding your properties file. I'm guessing that myProp.properties is in the root of your project, if that's the case, you need a preceding slash:
InputStream stream = loader.getResourceAsStream("/myProp.properties");
How to read data from java properties file using Spring Boot
You can use @PropertySource
to externalize your configuration to a properties file. There is number of way to do get properties:
1.
Assign the property values to fields by using @Value
with PropertySourcesPlaceholderConfigurer
to resolve ${}
in @Value
:
@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {
@Value("${gMapReportUrl}")
private String gMapReportUrl;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
2.
Get the property values by using Environment
:
@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {
@Autowired
private Environment env;
public void foo() {
env.getProperty("gMapReportUrl");
}
}
Hope this can help
How to use Java property files?
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) {
...
}
Iterate as:
for(String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
System.out.println(key + " => " + value);
}
Java - purpose of property files
In general, property files are maintained in file system(Windows/Linux), but your class files are packaged as part of jar/war file. If you hardcode the values inside the classes, then you need to change the property value in the class, then recompile and repackage the jar/war file and test and redeploy the application.
why can't we have those values in Java class?
This is like hardcoding the values (inside class/jar/war) as you need to recompile the Java code and redeploy the application everytime a property value changes.
What benefits does a property file give over Java files?
You don't need to recompile the code, rather they can be updated from the property file (they reside outside class/jar/war) itself and you can restart the server/program.
Best way to access properties from property file in java
I can suggest two approaches:
1. Define a utility method which will take String as parameter and return value from properties.
For Example:
public static String GetValue(String key) {
return properties.getProperty(key);
}
And now you can use this function on callers
String value = GetValue("key"); // properties.getProperty("key");
Define above method and in addition create one class Called Constants(or something suitable). Define all your Keys here as Static final variable.
public class Constants
{
public static final String KEY = "key";
public static final String KEY2 = "key2";
}
and now make call for getting value using these variable instead of string:
String value = GetValue(KEY); //GetValue("key");
If you do only option 1, your code is becoming more readable. But I will recommend 2nd option, which is making your code readable as well as maintainable.
You can easily do following operation :
- Update property name
- No need to worry about mistyping key etc.
Creating a properties file in Java and eclipse
- Create a new file from file menu Or press Ctrl+N
- In place of file name write config.properties then click finish
Then you can add properties your property file like this
dbpassword=password
database=localhost
dbuser=user
Example of loading properties
public class App {
public static void main(String[] args) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("database"));
System.out.println(prop.getProperty("dbuser"));
System.out.println(prop.getProperty("dbpassword"));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Why use properties file instead of placing properties as fields in java class?
Because Java source file needs recompilation and deployment to make a change.
If your code reads a property file, it's:
Easier to change the value.
Allows reading property file from outside jar file (if configured), so it can be changed without changing a deployed jar file.
I mean, you did call it a "configuration value", right?
That implies that you can "configure" it when you deploy the code.
Related Topics
Why Doesn't Java Offer Operator Overloading
How to Count the Number of Occurrences of an Element in a List
Httpurlconnection Doesn't Follow Redirect from Http to Https
"Code Too Large" Compilation Error in Java
How to Switch Between Frames in Selenium Webdriver Using Java
How to Subtract X Days from a Date Using Java Calendar
How Does Cloneable Work in Java and How to Use It
Why Java Needs Serializable Interface
Real World Example of the Strategy Pattern
How to Implement Constants in Java
How to Override Class Variables in Java
Javafx Fxml Controller - Constructor VS Initialize Method
How to Check If the User Is Pressing a Key
Regex to Match a C-Style Multiline Comment
Collect Successive Pairs from a Stream
Initialising a Multidimensional Array in Java
How to Switch to the New Browser Window, Which Opens After Click on the Button