Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

properties file

 
dale con
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all

i've created a properties file and need to read it in my code. But i don't want to hardcode the file location. Is there anyway i can do this

Many thanks



My code

String propFile = "myprops.properties";

Properties properties = new Properties();

try
{
properties.load(new FileInputStream("C:\\Properties\\"+propFile));
}
catch (IOException e)
{
System.out.println("Properties exception " + e.toString());
}

// read values from properties file
a = properties.getProperty("a");
b = properties.getProperty("b");
c = properties.getProperty("c");
}
 
Timmy Marks
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are several ways to do this. You could take the name and location of the file as a command line option, or (especially if it isn't your top level class) you could make the name of the file an attribute of the instance of your class. You could also specify the name of a settings file that you will read to find out the name of the properties file (which is somewhat redundant, but still possible)
 
Rick Beaver
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at Class.getResource() and Class.getResourceAsStream() in the API docs. You can use these methods to access a relative URL as long as the file is visible to your ClassLoader.
 
dale con
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, i'm being a bit dumb here

>you could make the name of the file an attribute of the instance of your >class.

I don't understand what you mean


I'm not understanding the ClassLoader. I've looked at the api's and i'm not clear where i put the properties file on my system and how i reference it.

Any help much appreciated
 
Timmy Marks
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do you know which directory to look in? Are you specifying it so any user can load in his properties, or are you deciding it at runtime based on a variable? You can load files from relative paths. Have you thought of that?
 
dale con
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I put the poperties file in my WEB_INF\classes folder

and did this

properties.load(ClassLoader.getSystemResourceAsStream(propFile));

and it finds it

cheers
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic