Arvind
Arvind

Reputation: 6474

java-how to specify the path to a file that i have stored along with source code

I am trying to get the path to a file named "policy.local" which I have stored in /com/package/

I want to specify the path to the above file from a class named "com.package.class". (So this class and the file are in the same folder)... How do I specify the path to the policy.local file, in the java code of class com.package.class?

Upvotes: 0

Views: 1682

Answers (2)

Andremoniy
Andremoniy

Reputation: 34900

A simple way: create an empty class (with no methods and fields) in the package "/com/package/" if this package doesn't contain any classes, or use any of them, if they are present. Then do the next:

ClassName.class.getResource("policy.local").toString()

This will give you a form of an absolute path of your file, something like this:

file:/C:/sandbox/xxx/com/package/policy.local

Upvotes: 2

Sean Connolly
Sean Connolly

Reputation: 5803

As your class and the file (resource) are in the same package, you can get at it with:

getClass().getResource("policy.local")

If the class and the resource are not in the same package, you will want to use:

getClass().getClassLoader().getResource("com/package/policy.local");

Upvotes: 1

Related Questions