I dont really understand why but I get file not found when I try to load the properties.
I put a file called c24.properties in the resources folder alongside with application.properties
private static final String PROP = "c24.properties";
private Properties properties;
// Constructor
public KTServices() {
try {
properties = new Properties();
properties.load(new FileInputStream(PROP)); // FILE NOT FOUND??
} catch (IOException e) {
e.printStackTrace();
}
}
Any help? Why it doesn't find? This is a Spring Boot maven project
PS: I just checked the /target and the c24.properties is in the root folder as expected
Properties appProps = new Properties();
try {
appProps.load(Thread.currentThread().getContextClassLoader().getResource("app.properties").openStream());
} catch (IOException var3) {
this.log.error("properties file not found", var3.toString());
}
return appProps;
If the file is in the same directory as the class file, you can use the following:
properties.load(KTServices.class.getResourceAsStream(PROP));
Any property files that are outside the jar requires a full path to locate successfully.
I tried best couldn't find a complete instructions on how to config a properties file with Maven,Testng.
Here are what I did and the exception I got:
from TestNG for suite, added
content of the config file:
user=testuser
password=pswd
pom.xml
src/test/resources
true
in code:
#BeforeTest #Parameters(value = { "config-file" })
public void initFramework(String configfile) throws Exception
{
InputStream stream = Config.class.getResourceAsStream("/config.properties");
Properties properties = new Properties();
try {
properties.load(stream);
String user = properties.getProperty("user");
String password = properties.getProperty("password");
System.out.println("\nGot User FirstName+LastName shows as:"+ user +"\n" + password + "===========");
} catch (IOException e) {
e.printStackTrace();
// You will have to take some action here...
}
}
Here is what I got when compile:
org.testng.TestNGException:
Parameter 'config-file' is required by #Configuration on method initFramework but has not been marked #Optional or defined
Question:
I think I got all options mixed but really wanted a working way to read the parameter for Java/Selenium/TestNG/Maven.
Properties CONFIG= new Properties();
FileInputStream ip = new FileInputStream("C://config.properties");
CONFIG.load(ip);
//Now simply read through property file:-
String user = CONFIG.getProperty("user");
String password = CONFIG.getProperty("password");
//To write property file:-
CONFIG.setProperty("user","newbie1");
CONFIG.setProperty("password","secret123");
Currently I am trying to read my config file from root of project directory, in order to make this actual configuration I want to move this to external location and then read from there.
Adding a complete path in following code throws out error :
package CopyEJ;
import java.util.Properties;
public class Config
{
Properties configFile;
public Config()
{
configFile = new java.util.Properties();
try {
// configFile.load(this.getClass().getClassLoader().getResourceAsStream("CopyEJ/config.properties"));
Error Statement ** configFile.load(this.getClass().getClassLoader().getResourceAsStream("C://EJ_Service//config.properties"));
}catch(Exception eta){
eta.printStackTrace();
}
}
public String getProperty(String key)
{
String value = this.configFile.getProperty(key);
return value;
}
}
Here's the error:
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:365)
at java.util.Properties.load(Properties.java:293)
at CopyEJ.Config.<init>(Config.java:13)
at CopyEJ.CopyEJ.main(CopyEJ.java:22)
Exception in thread "main" java.lang.NullPointerException
at java.io.File.<init>(File.java:194)
at CopyEJ.CopyEJ.main(CopyEJ.java:48)
How can I fix this ?
The purpose of method getResourceAsStream is to open stream on some file, which exists inside your jar. If you know exact location of particular file, just open new FileInputStream.
I.e. your code should look like:
try (FileInputStream fis = new FileInputStream("C://EJ_Service//config.properties")) {
configFile.load(fis);
} catch(Exception eta){
eta.printStackTrace();
}
This line requires your config.properties to be in the java CLASSPATH
this.getClass().getClassLoader().getResourceAsStream("C://EJ_Service//config.properties")
When it is not, config.properties won't be accessible.
You can try some other alternative and use the configFile.load() function to read from.
One example would be:
InputStream inputStream = new FileInputStream(new File("C:/EJ_Service/config.properties"));
configFile.load(inputStream);
If I have the following directory structure,
+src
++com.foo.util
+++FooProperties.java
+foo.properties
How do I reference foo.properties as a resource stream in FooProperties? I've tried adding it to the classpath and referencing it as such,
FooProperties.class.getResourceAsStream("/foo.properties")
but I get a NullPointerException. What am I doing wrong?
If you want to keep the properties file outside the src(same level as src), then you can fetch your properties file this way:-
try {
InputStream fileStream = new FileInputStream(new File(
"test.properties"));
Properties props = new Properties();
props.load(fileStream);
String myPropValue = (String) props.get("test.prop");
System.out.println(myPropValue);
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
Hope it helps. You can even edit the properties file using the above method(no absolute path required).
I need to read a properties files that's buried in my package structure in com.al.common.email.templates.
I've tried everything and I can't figure it out.
In the end, my code will be running in a servlet container, but I don't want to depend on the container for anything. I write JUnit test cases and it needs to work in both.
When loading the Properties from a Class in the package com.al.common.email.templates you can use
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("foo.properties");
prop.load(in);
in.close();
(Add all the necessary exception handling).
If your class is not in that package, you need to aquire the InputStream slightly differently:
InputStream in =
getClass().getResourceAsStream("/com/al/common/email/templates/foo.properties");
Relative paths (those without a leading '/') in getResource()/getResourceAsStream() mean that the resource will be searched relative to the directory which represents the package the class is in.
Using java.lang.String.class.getResource("foo.txt") would search for the (inexistent) file /java/lang/String/foo.txt on the classpath.
Using an absolute path (one that starts with '/') means that the current package is ignored.
To add to Joachim Sauer's answer, if you ever need to do this in a static context, you can do something like the following:
static {
Properties prop = new Properties();
InputStream in = CurrentClassName.class.getResourceAsStream("foo.properties");
prop.load(in);
in.close()
}
(Exception handling elided, as before.)
The following two cases relate to loading a properties file from an example class named TestLoadProperties.
Case 1: Loading the properties file using ClassLoader
InputStream inputStream = TestLoadProperties.class.getClassLoader()
.getResourceAsStream("A.config");
properties.load(inputStream);
In this case the properties file must be in the root/src directory for successful loading.
Case 2: Loading the properties file without using ClassLoader
InputStream inputStream = getClass().getResourceAsStream("A.config");
properties.load(inputStream);
In this case the properties file must be in the same directory as the TestLoadProperties.class file for successful loading.
Note: TestLoadProperties.java and TestLoadProperties.class are two different files. The former, .java file, is usually found in a project's src/ directory, while the latter, .class file, is usually found in its bin/ directory.
public class Test{
static {
loadProperties();
}
static Properties prop;
private static void loadProperties() {
prop = new Properties();
InputStream in = Test.class
.getResourceAsStream("test.properties");
try {
prop.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public class ReadPropertyDemo {
public static void main(String[] args) {
Properties properties = new Properties();
try {
properties.load(new FileInputStream(
"com/technicalkeeda/demo/application.properties"));
System.out.println("Domain :- " + properties.getProperty("domain"));
System.out.println("Website Age :- "
+ properties.getProperty("website_age"));
System.out.println("Founder :- " + properties.getProperty("founder"));
// Display all the values in the form of key value
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
System.out.println("Key:- " + key + "Value:- " + value);
}
} catch (IOException e) {
System.out.println("Exception Occurred" + e.getMessage());
}
}
}
Assuming your using the Properties class, via its load method, and I guess you are using the ClassLoader getResourceAsStream to get the input stream.
How are you passing in the name, it seems it should be in this form: /com/al/common/email/templates/foo.properties
I managed to solve this issue with this call
Properties props = PropertiesUtil.loadProperties("whatever.properties");
Extra, you have to put your whatever.properties file in /src/main/resources
Nobody mentions the similar but even simpler solution than above with no need to deal with the package of the class. Assuming myfile.properties is in the classpath.
Properties properties = new Properties();
InputStream in = ClassLoader.getSystemResourceAsStream("myfile.properties");
properties.load(in);
in.close();
Enjoy
use the below code please :
Properties p = new Properties();
StringBuffer path = new StringBuffer("com/al/common/email/templates/");
path.append("foo.properties");
InputStream fs = getClass().getClassLoader()
.getResourceAsStream(path.toString());
if(fs == null){
System.err.println("Unable to load the properties file");
}
else{
try{
p.load(fs);
}
catch (IOException e) {
e.printStackTrace();
}
}