JAVA gets the folder where the jar package resides

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.