For some reason i have to place my *.properties
files outside of java app. When the file km.properties
resides in java/src/resources/km.properties
the code reads the file but when i place the same file in C:\Users\abc\Desktop\km.properties
it throws
Exception: java.io.FileNotFoundException: property file 'C:\Users\abc\Desktop\km.properties' not found in the classpath
Exception in thread "main" java.lang.NullPointerException
at com.ir.Constants.<init>(Constants.java:44)
at com.Constants.main(Constants.java:64)
here is my code
public class Constants {
public Constants(){
System.out.println(System.getenv("km_config"));
try {
Properties prop = new Properties();
String propFileName = System.getenv("km_config");
inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
}
catch (IOException e) {
System.out.println("Exception: " + e);
}
catch (Exception e) {
System.out.println("Exception: " + e);
} finally {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
Constants c = new Constants();
System.out.println(Constants.DB_PATH1);
System.out.println(Constants.GIT_REPO_PATH);
System.out.println(Constants.GIT_MAIN_BRANCH_NAME);
System.out.println(Constants.TAGGER_PATH);
}
Constants.java:44
is
inputStream.close();
Constants.java:64
is
Constants c = new Constants();
please help me i need to place km.properies
file any where outside of the java app
command results in
echo %km_config%
C:\Users\abc\Desktop\km.properties
The API ClassLoader::getResourceAsStream(String)
has a search path which is the classpath. Actually you are right that the configuration file should not be bundled with your .class files and read from the filesystem of the target machine instead.
Thus your API call becomes:
Properties conf = new Properties();
conf.load(new InputStreamReader(new FileInputStream(new File(file)));
Note: I did not specify a charset for converting the stream of bytes to a stream of character because I want the JVM to pick whatever character is the default for the system.
For testing I suggest you:
-Dfile=C:\Users\me\Desktop\km.properties
)