0

I'm trying to get the file location of a jar inside a jar. This is the code I have that gets the location of the jar file, then I direct it to my Lib folder, and according to my code, the file location does not exit.

    private File getThisJar() {
         return new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
    }
    
    public void handle() {
         File jar = new File(getThisJar() + "/lib", "JDA.jar");
         if (!jar.exists())
             return;
    }

In this the .exists method returns false and I'm not sure exactly what I'm doing wrong.

Marc Le Bihan
  • 2,308
  • 2
  • 23
  • 41
Spencer Nold
  • 41
  • 1
  • 7
  • 2
    A jar is a file; the entries in a jar are NOT files and cannot be accessed using `File` because `File` only accesses files. If you extract the sub-jar from the outer jar to an actual file, you can then access that file using `File` because it's a file. Otherwise you may want to access the entry in the outer jar, but if so you can't use `File`. _Since_ the outer jar is in the classpath you can access the _data_ of an entry using `getResourceAsStream`. – dave_thompson_085 Oct 11 '20 at 04:15
  • Dave is right! Another possible solution: you can unzip the jar programmatically and then check the existence of the other jar! – Onur Baştürk Oct 11 '20 at 06:16
  • How would I do that Onur? I'm using the File to get an instance of a JarFile, and the JarFile constructor parameter takes a file. – Spencer Nold Oct 11 '20 at 06:50
  • 1
    `JarFile` simply does not support a jar inside a jar. You can use `getResourceAsStream` to get a stream and wrap it in a `JarInputStream`, if processing the contained entries linearly is feasible. The only other option is the filesystem API, [but you need to know the obstacles](https://stackoverflow.com/a/58980655/2711488). – Holger Oct 13 '20 at 08:22

0 Answers0