File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes properties file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "properties file" Watch "properties file" New topic
Author

properties file

dale con
Ranch Hand

Joined: Apr 15, 2005
Posts: 93
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

Joined: Dec 01, 2003
Posts: 226
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

Joined: Dec 14, 2004
Posts: 464
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.


ph34r my 133t j4v4 h4><0r1ng sk177z
dale con
Ranch Hand

Joined: Apr 15, 2005
Posts: 93
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

Joined: Dec 01, 2003
Posts: 226
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

Joined: Apr 15, 2005
Posts: 93
I put the poperties file in my WEB_INF\classes folder

and did this

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

and it finds it

cheers
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: properties file