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
You can determine the absolute path of any file in Windows by right-clicking a file and then clicking Properties. In the file properties first look at the "Location:" which is the path to the file.
The getAbsolutePath() method is a part of File class. This function returns the absolute pathname of the given file object. If the pathname of the file object is absolute then it simply returns the path of the current file object. For Example: if we create a file object using the path as “program.
An absolute path is defined as the specifying the location of a file or directory from the root directory(/). In other words we can say absolute path is a complete path from start of actual filesystem from / directory.
InputStream realData = getClass(). getClassLoader(). getResourceAsStream("testfile. xml");
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");
I don't know if this is the best way, but it works for me :)
String path = new File("").getAbsolutePath() + File.separator + "docroot";
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With