I am trying to get deploy root directory of my servlet based project from java. I am using the following lines of codes to get the path details.
Type 1:
File directory = new File (".");
try {
System.out.println ("Current directory's canonical path: "
+ directory.getCanonicalPath());
System.out.println ("Current directory's absolute path: "
+ directory.getAbsolutePath());
}catch(Exception e) {
System.out.println("Exceptione is ="+e.getMessage());
}
Type 2:
String currentDir = System.getProperty("user.dir");
System.out.println("Current dir using System:" +currentDir);
While executing the above codes from main class i am getting user directory. When i executes from server side, gets as, "Current dir using System:D:\Apache Tomcat 6.0.16\bin". But my project is located in D:\Apache Tomcat 6.0.16\wepapps\SampleStructs
.
Please give me any suggestions for this and help me out of this.
First of all, the main cause of your problem is the difference between current working directory and the location of your executable. You should know that current working directory in Linux is not the directory where the executable is, but instead the current directory where the program was started from.
As an example, let's say you have a program current
which prints out the current directory and it is located in /home/user/scripts/
.
If you do this:
cd /home/user/scripts
./current
It will print out: /home/user/scripts/
But, if you do this:
cd /home/user/
scripts/current
The output will be: /home/user/
As to the possible solutions, some of them I found useful are:
ClassLoader.getResourceAsStream()
for more infogetClass().getProtectionDomain().getCodeSource().getLocation().getPath()
. See more about this approach and some possible issues here: How to get the path of a running JAR file?
It because when you execute from main class everything is fine, but this code runs on server it looks into current directory and current the directory structure is Apache 'bin' from where you have started the server(run.bat).
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