Path: csiph.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Nigel Wade Newsgroups: comp.lang.java.programmer Subject: Re: How do I get the name and path of the running jar file? Date: Mon, 12 Dec 2016 09:51:35 +0000 Lines: 36 Message-ID: References: <0564c643-106a-499a-833e-dffe34d1e915@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 8bit X-Trace: individual.net UQAx4KVdlzlAXH1Gr3mWGA16pDZnnP28h3ifpnlT50Y4HSiDv+ Cancel-Lock: sha1:toPv2htIaLEblUNwAyDbl6h1tnI= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Thunderbird/45.4.0 In-Reply-To: Xref: csiph.com comp.lang.java.programmer:36086 On 12/12/16 01:24, Arne Vajhøj wrote: > On 12/8/2016 8:20 AM, Nigel Wade wrote: >> On 07/12/16 02:18, Arne Vajhøj wrote: >>> You will get the full name including path of the jar with one of the >>> following: >>> >>> String path = >>> MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath(); >>> >>> >>> String path = >>> MyClass.class.getClassLoader().getResource("mypackage/MyClass.class").getPath(); >>> >>> >>> The format is sligthly different. The first is probably more convenient >>> as you would not need to truncate at the '!'. >> >> Both methods CodeSource.getLocation() and ClassLoader.getResource() >> return a URL, which will be URL encoded. So the path ought to be >> URLdecode'd otherwise there may be problems with any characters in the >> path which URL has encoded. >> >> Also, in the case of ClassLoader.getResource(), when executed from a jar >> it will be of type "jar", and from class files it will be of type >> "file". This will probably come into play when you run the code in an >> IDE. NetBeans (I don't know about Eclipe) runs class files, not jars. >> You will probably need to handle each case differently. > > Good points. > > But it should be possible to extract the information in the desired > format. > It is definitely possible, but it's still good to be aware of the caveats before they cause you problems.