Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #9095

Re: get path of a Jar file

From Martin Gregorie <martin@address-in-sig.invalid>
Newsgroups comp.lang.java.programmer
Subject Re: get path of a Jar file
Date 2011-10-22 21:19 +0000
Organization UK Free Software Network
Message-ID <j7vc04$vse$1@localhost.localdomain> (permalink)
References <j7u3th$9dr$1@online.de>

Show all headers | View raw


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       |

Back to comp.lang.java.programmer | Previous | NextPrevious in thread | Next in thread | Find similar


Thread

get path of a Jar file Philipp Kraus <philipp.kraus@flashpixx.de> - 2011-10-22 11:54 +0200
  Re: get path of a Jar file Lew <lewbloch@gmail.com> - 2011-10-22 08:52 -0700
  Re: get path of a Jar file Martin Gregorie <martin@address-in-sig.invalid> - 2011-10-22 21:19 +0000
  Re: get path of a Jar file Steven Simpson <ss@domain.invalid> - 2011-10-24 21:07 +0100
    Re: get path of a Jar file Philipp Kraus <philipp.kraus@flashpixx.de> - 2011-10-30 18:49 +0100

csiph-web