S Singh
S Singh

Reputation: 1473

Java - Get server absolute path

How to get the absolute path of server location in my machine?

Suppose I am using glassfish server then I need to get absolute path of glassfish docroot location as below:

C:\glassfish3\glassfish\domains\domain1\docroot

At run time, I need to create file on that location using java io package like:

C:\glassfish3\glassfish\domains\domain1\docroot\myfile.txt

Upvotes: 5

Views: 30182

Answers (6)

codeplumber
codeplumber

Reputation: 469

If you use GlassFish to start GlassFish, i.e. use asadmin start-domain|start-instance then we offer the following iron-clad guarantee:

The current working directory of the JVM is absolutely, positively guaranteed to be the config directory of the domain or server. In the default case that would be:

c:/glassfish3/glassfish/domains/domain1/config

If you want to write something to (the default) docroot, you can do this:

File f = new File("../docroot/yourfile");

Another option that is guaranteed to always work in every scenario even if you start the server with java directly (e.g. java -jar glassfish.jar) is to use the value of the System Property like so:

File f = new File(System.getProperty("com.sun.aas.instanceRoot") + "/docroot/yourfile");

Upvotes: 5

wutzebaer
wutzebaer

Reputation: 14863

I had an similar problem and ended up with using

path = getClass().getProtectionDomain().getCodeSource().getLocation()

because I needed the path on a static function. This points somwhere to the WEB-INF/classes directory. With this you could point to something like path.subString(0,path.indexOf("WEB-INF")).

One problem that I had with this: When running a test from Eclipse, it pointed me to the "build" directory of the project.

Upvotes: 1

Gökhan E.
Gökhan E.

Reputation: 75

you can try following:

System.getProperty("catalina.base");

And you can find other properties by watching following variable in debug mode.

Properties properties = System.getProperties();

Upvotes: 1

Scruger
Scruger

Reputation: 159

I don't know if this is the best way, but it works for me :)

String path = new File("").getAbsolutePath() + File.separator + "docroot";

Upvotes: 1

Jim Garrison
Jim Garrison

Reputation: 86754

This is a very bad idea. If you are running in a WAR or EAR file the docroot will not be on a writable filesystem. Assuming this is the case may lead to headaches later.

Use a different method, such as a servlet initialization parameter, to specify a writable filesystem location.

Upvotes: 0

Yogesh Prajapati
Yogesh Prajapati

Reputation: 4870

For that you need not to go for complete path because

when you are creating file than by default it will create at ROOT of you server

which is C:\glassfish3\glassfish\ here.

hope this will help you.

Upvotes: -1

Related Questions