On 07/12/16 02:18, Arne Vajhøj wrote:
> On 12/6/2016 3:41 PM,
triciac...@gmail.com wrote:
>> I am writing a program that has sound files with type names and
>> numbers like, "win1.wav" and "lose3.wav". I want the program to get
>> the name and path of the running jar file so I can programmatically
>> choose a random sound file of a specified type that is packaged
>> inside the jar file without having to hardcode it myself. Everything
>> I've tried works in Eclipse, but not after it is exported because it
>> doesn't find the name of the jar file, only the path. Is there a way
>> I can get the name AND path of the jar file? Could I search through
>> the jar file packages without using the name and path?
>
> 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.
This is definitely the preferred method if you know which file you want to open.