Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!usenet.ukfsn.org!not-for-mail From: Martin Gregorie Newsgroups: comp.lang.java.programmer Subject: Re: get path of a Jar file Date: Sat, 22 Oct 2011 21:19:00 +0000 (UTC) Organization: UK Free Software Network Lines: 51 Message-ID: References: NNTP-Posting-Host: 84.45.235.129 Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Trace: localhost.localdomain 1319318340 32654 84.45.235.129 (22 Oct 2011 21:19:00 GMT) X-Complaints-To: usenet@localhost.localdomain NNTP-Posting-Date: Sat, 22 Oct 2011 21:19:00 +0000 (UTC) User-Agent: Pan/0.135 (Tomorrow I'll Wake Up and Scald Myself with Tea; GIT 30dc37b master) Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:9095 On Sat, 22 Oct 2011 11:54:57 +0200, Philipp Kraus wrote: One obvious thing to do is to get rid of the hex encoding for space before starting to work on the string: String jarfile = Class.forName("class_within_the_jar").getResource("").toString(); jarfile = jarfile.replace("%20", " "); But using a magic constant like 9 is asking for trouble > jarfile = jarfile.substring(9, jarfile.lastIndexOf(".jar!")) + ".jar"; would be better written as: static final int START_POINT = 2 /* number of names to skip */ String[] pathPieces = jarfile.split(File.separator); StringBuilder sb = new StringBuilder(); int last = jarfile.length() - 1; for (int i = START_POINT; i < last; i++) sb.append(pathPieces[i] + File.separator); sb.append(pathPieces[last]); String relativePath = sb.toString(); which may be longer, but is a lot readable. It may even be portable between Windows and *NIX systems provided you want a relative path that, on a *NIX, corresponds to ~/Java\ Files\myjar.jar but to myuser\Java Files\myjar.jar on Windows. Note that my solution uses nothing but String methods. If you haven't yet installed the SDK documentation where its readily available, I suggest you do so and get familiar with using it. > I need a solution to detect the location of a Jar File in a class. > ..but why do you want a relative path name rather than an absolute one? Both *NIX and Windows systems are happy with absolute names. -- martin@ | Martin Gregorie gregorie. | Essex, UK org |