Findout the "codebase" ?

M

Meir

Hi,

I need to findout the exact folder from which my classes are loading.
This could be a regular folder containing my .CLASS files,
or a JAR file.

How is it done ?
Can I know whether it is a JAR file ?
Can I distinguish the file-system hierarchy from the JAR
internal hierarchy ?

Alternatively: Is there a current-working-dir in Java applications ?
How do I get/set ?

Thanks in advance,
Meir
 
J

Jon A. Cruz

Meir said:
Hi,

I need to findout the exact folder from which my classes are loading.
This could be a regular folder containing my .CLASS files,
or a JAR file.

Why?

Why do you need to?

How is it done ?
Can I know whether it is a JAR file ?
Can I distinguish the file-system hierarchy from the JAR
internal hierarchy ?


The different thing to do is just call getClass().getResouce() on some
class in your code.
 
T

Thomas Weidenfeller

It finds-out the folder from which the main module is loading, and
uses a relative sub-floder named "INI".

If you want to use files, and not the new resource API:

(a) Use the class loader of what you call the "main modul" (there is no
such thing in Java), and let it figure out the location, and

(b) use Properties files and the properties class:

If you have an instance (e.g. if you are in a non-static method)

InputStream in = this.getClass().getResourceAsStream(
"/properties/config.properties" // your properties file name
);

If you don't have an instance (e.g. in a static method):

InputStream in = <name-of-your-class>.class.getResourceAsStream(
"/properties/config.properties" // your properties file name
);

(replace <name-of-your-class> with what it says). And then:

Properties configData = new Properties();
configData.load(in);
in.close();

And that's it. It will look similar if you want to stick with your XML.

Note that you are supposed to use "/" and not "\\", even if you are on
windows. This is a resource name, and not a file name. When the class
loader searches for the resource, it converts the resource name to a
file name, if necessary (actually, it converts it to a URL, but that is
a detail).

Using the class loader to look up the file works, because this is the
same mechanism that is used to locate the class file itself. You don't
have to know where it is, as long as the VM knows. And the VM has to
know, otherwise it can't run your code.

For more details (e.g. using a laeading '/' or not using one), you want
to read the Class and ClassLoader API documentation.

/Thomas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top