I believe a lot of beginners may be like me, just start writing Java programs, if you need to get the current class in the directory (for example: I am accustomed to the development of the log will be written in the current program directory, dynamic Setup folder and log file txt), it is not a problem, but packaged into a jar file, The problem comes, always error when getting the path, because the path is not correct, or the resulting path is not what you want (example: a similar path obtained in a jar package:file:/h:/java/test1/myjar/demo1_fat.jar!/ Main/main.jar and directly in the Eclipse runtime get:/h:/java/test1/demo1/bin/ actually packaged, the path you want is:H:/java/test1/myjar )。
So my way is to deal with the string, the specific code is as follows:
Public String Syspath ()
{
String Path=this.getclass (). Getprotectiondomain (). Getcodesource (). GetLocation (). GetPath ();
if (Path.touppercase (). IndexOf (". JAR ")!=-1)
{
Try
{
Interception ". The string before the first occurrence of the jar "
String strpath=path.substring (0, Path.touppercase (). IndexOf (". Jar". toUpperCase ()));
System.out.println (strpath);
Get the previous level folder for the. jar Package
Path=strpath.substring (0,strpath.lastindexof ("/") +1);
}
catch (Exception e)
{
Return "Error:" +e.tostring ();
}
}
return path;
}
This method mainly implements the path string of the original jar package to be processed and returned. If it is run directly in Eclipse, it is returned as is.
Results such as:
JAVA gets the folder where the jar package resides