Re: get path of a Jar file
Philipp Kraus wrote:
I would like to extract a directory of a Jar file. I read the path of
my Jar file with:
String l_jarfile =
Class.forName("class_within_the_jar").getResource("").toString();
l_jarfile = l_jarfile.substring(9,
l_jarfile.lastIndexOf(".jar!")) + ".jar";
This does not work on MS Windows systems (unix and OSX work correct
with this code).
If the Jar files is stored under a path like "C:\Users\myuser\Java
Files\myjar.jar" (with a space)
the JarFile-Object can't locate the file, because the space within the
directory is changed to %20
I need a solution to detect the location of a Jar File in a class. How
can i [sic] Do this in a correct way?
Well, you could look for the "%20" I suppose, but your code looks messy and=
unnecessary.
Sometimes it pays to take a step back. Just exactly why do you need the JA=
R file? What does that give you that you cannot get any other way?
'Class.forName()' loads a class. Every time you execute that line, you're =
attempting to load the class. Why do you need to load the class again and =
again?
Loading classes usually is only done when the class will be used in the pro=
gram. It only needs to be done once per class (per classloader).
Your variable names do not conform to the Java conventions for naming. Don=
't use underscores in non-constant variables; use camel case ("camelCase") =
to distinguish word parts, with the first letter lower case for non-constan=
t variables and for methods, upper case for types. (Constant variables use=
ALL UPPER case with underscores to separate word parts instead of camel ca=
se.)
Your portability problem may be a consequence of your magic constants (9, "=
..jar!"). I don't know. Are you sure they're the same for Windows?
Have you traced through log statements or a debugger what the various inter=
mediate values are? What are they?
But the real question is what do you want from this information? I am not =
able to come up with a scenario where knowing the JAR path helps a program,=
not to retrieve resources or to load classes. However, you seem to want i=
t, so since the JAR is in your classpath, why don't you just look for match=
ing substrings against the JAR names in your classpath?
--
Lew