I am trying to get current directory of my Project from java. I am using the following lines of codes to get the path details.
Type 1:
File directory
you can use this code
String absolutePath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
absolutePath = absolutePath.substring(0, absolutePath.lastIndexOf("/"));
this code is working before for me! it will return the full path of folder in windows or linux.
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?There are different context we are talking about here. 1. Running the application in standalone mode. 2. Running the application in container on server side. In #1, The application is run from the directory it is invoked.
But #2 case, the application is run relative to the container, so you see the location of server directory. This also shields the application code.
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).