1

I am trying to read a config file based on the code here:

http://www.opencodez.com/java/read-config-file-in-java.htm

So I found that if the config.cfg is in same directory as of where I am running the code, then everything is fine but if the config is at different directory

example: /path/to/config.cfg 

I get this error:

java.lang.NullPointerException at java.util.Properties$LineReader.readLine(Properties.java:418) at java.util.Properties.load0(Properties.java:337) at java.util.Properties.load(Properties.java:325) at packagename.conf.Config.<init>(Config.java:14) at packagename.conf.Config.main(Config.java:30) 

My guess is it is not able to find the file. But how do I modify the above code to read config file from a different folder? Thanks

Edit: Code from the link:

import java.util.*; import java.util.Properties; public class Config { Properties configFile; public Config() { configFile = new java.util.Properties(); try { configFile.load(this.getClass().getClassLoader(). getResourceAsStream("myapp/config.cfg")); }catch(Exception eta){ eta.printStackTrace(); } } public String getProperty(String key) { String value = this.configFile.getProperty(key); return value; } } 
3
  • The actual code you use for opening the file would be very helpful here Commented Jan 3, 2013 at 23:37
  • @AlexanderWeinert: HI.. its the same code from the link. I just copy pasted :) Commented Jan 3, 2013 at 23:38
  • It will definitely throw FileNotFoundException. To get rid of this either gave it a absolute path or specific relative path Commented Jan 3, 2013 at 23:38

1 Answer 1

4

The code that you posted expects the configuration-file to be on the classpath (that is, in the same sorts of places that Java looks for your .class files). So, you can either include the directory containing the configuration-file in the classpath:

java -classpath .:/path/to packagename.conf.Config 

Or else you can modify the code to expect the configuration-file to be a regular filesystem file:

final InputStream cfg = new FileInputStream("/path/to/config.cfg"); try { configFile.load(cfg); } finally { cfg.close(); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.