I am trying to read a property file in a seperate "GetConfigProperties" class file and passing the value to the main function "LoginTest.java". But I am not able to get the expected property value and there is no errors displayed in the code as well.
I have the property file in src/config.properties I have the main function in src/com.automation.test -> LoginTest.java I have the java function to read property file in src/com.library.helper -> GetConfigProperties.java
My code to read Config property is given below
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class GetConfigProperties {
//protected File file = new File("config.properties");
protected static Properties props = new Properties();
InputStream is = GetConfigProperties.class.getResourceAsStream("/config.properties");
public static String extractUrlData(){
String webUrl = props.getProperty("webUrl");
return webUrl;
}
}
-- Also, I imported this class file in the main LoginTest.java and try to access the get the data as GetConfigProperties.ExtractUrlData() but failed.
P.S - I looked into many of the questions and answers and since I am totally new to Java couldn't understand them as everything seems to be unique.
Solved
Here's how you access the properties:
GetConfigProperties.ExtractUrlData();
This calls the static method ExtractUrlData() (which should be called extractUrlData() to conform to Java naming conventions). Nowhere do you call the GetConfigProperties() method of GetConfigProperties, which is where the Properties object is populated.
You should choose: either the Properties is static, and it should be populated when the class is loaded, by a static method, or a static block:
private static Properties props = createAndPopulateProperties();
or it should be an instance field, that can be populated by the class constructor or one of its instance methods that would initialize the object.
Another problem is that there is a very low chance that the user running your app has the file in exactly the same folder as you (if he's even running Windows). You should bundle the properties file with the .class files of the app (in the same jar, or the same directory), and use the class loader to load the resource:
InputStream is = GetConfigProperties.class.getResourceAsStream("/config.properties");
No comments:
Post a Comment