简体   繁体   中英

Find file in external jar not in my classpath

I´m running some test and I need to get the path of a file that it´s in a jar lib that I have in my project as dependency.

This jar is not part of the classpath that I run.

If I try something like

val path =  getClass.getResource("h2-1.3.161.jar").getPath

in my test it does not work.

Any idea how to find a file inside a jar without be this jar part of your classpath?

Regards.

Using the solution of astrograph I manage to get this route

java -cp //file:/D:/Users/nb38tv/workspace/f2e-core/f2e-mock/f2e-test-framework/target/f2e-test-framework-1.8.3-SNAPSHOT.jar!/h2/sakila-h2-master/h2-1.3.161.jar -ifExists -tcp -web -tcpAllowOthers

But java complain since cannot find the jar.

If I remove the ! from the path I receive this error

Unrecognized option: -ifExists
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

Any idea?

Regards

Is the file a .class file? Can you open the file in your test? Can you instantiate a class from that jar file?

To get to the location of a class you can use the following method: System.out.println(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath());

It depends on what you mean by "find" the file.

If you mean "detect if the class file exists", then you can use the Java Zip file handling routines. Inside your code, open the Jar file as a Zip file.

If you mean "use the class file" within your program, and for some reason you cannot put it on your class file (perhaps it doesn't exist in that location at startup time) then you need to use an additional class loader which will look for the file after the file is present. To do this, I recommend you reuse at URLClassLoader, even if your file is local to the disk, just use a file:/// URL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM