Find file in external jar not in my classpath - java

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.

Related

Java FileNotFoundException in jar file

I’m working on a background Spring service that runs from the command line using a nohup command.
I’m hitting the following error:
java.io.FileNotFoundException: class path resource [templates/] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/Users/gestes/Documents/workspace/bge/bge-proj/myProcess/target/myProcess-0.2.2.jar!/templates/
The jar file is being created and does exist at:
/Users/gestes/Documents/workspace/bge/bge-proj/myProcess/target/myProcess-0.2.2.jar
When I extract the jar file contents, there is a /templates/ directory.
Looking at the exception, there is an “ ! “ after the jar file name, and I thought that tells what it can’t find, but clearly, it is there.
What am I missing?
If in your code you are trying to access the folder using a java File, you cannot do that. You need to use an inputStream
This is because things inside a Jar are not actually files on the disk. They are compiled inside of a jar. Yes it may be there when you extract the jar, but it's not actually a normal disk file when the jar is bundled

How to properly get resource Java project

In my project i currently have a setup using eclipse
But when i try to load the file "bg.png" by calling
getClass().getResource("/res/bg.png") or getClass().getResourceAsStream("/res/bg.png") I get a NPE
Can anyone tell me whats happening here? I never really thought there was much difference between how both methods locate their files
TIA
getClass().getResource[AsStream]() uses the class loader to load resources: the same mechanism as the one used to load class files based on the classpath.
So, to be able to load the resource, it must be in a jar file or under a directory that is part of the classpath. That is not the case here.
Move the res directory to the src directory: the file will then be in an Eclipse source directory, and Eclipse will "compile" it by simply copying the file to its bin/classes/whatever destination directory, which is in the classpath when running the application.

Java NoClassDefFoundError even when Jars in same folder

I have created a simple Java program (1 java file that contains the main() ), and I've included all Jar files in the same directory as the .class file. It is giving the NoClassDefFoundError message.
I've tried updating the Classpath to point to the directory, and I've also set "-cp ." to suggest that it look in the same directory as the .class file. However, the program still says it can't find the class def.
Any thoughts on what I should do?
Adding a folder tells java to look in that folder for .class files.
You can't reference .jar files via a folder name... Each .jar file's path must be listed on the CLASS_PATH explicitly.
this question's answer may be useful
When you try running a class from command line then a NoClassDefFound exception usualy means there is something wrong with your classpath.
You have explicitly define the classpath. You can do this in a few ways but the following way is the least prone to error:
Open a command shell and do the following:
1.) set classpath = {path to class files};{path to jars}
2.) java com.example.mainclass
Note: Even if your classes path and jar path is the same you need to specify them explicitly.
Note: If you have more then one jars place them in a folder say lib and add it to the classpath like: {path}/lib/* This will include all of the jar otherwise you have to specify them individually.
References: https://javarevisited.blogspot.com/2011/01/how-classpath-work-in-java.html
Import the following package:
Import java.lang.NoClassDefFoundError;

Problem with resources location difference in eclipse and JARs

I wrote a program that is based completely on a single text file: I read the file, store the information, then search the information, etc. So, for the program to work, the file just has to be present and detectable by the program.
I use eclipse, so I put the file is in the default resources map (src/main/resources). At the start of my program I create the file:
private static File textFile = new File("src/main/resources/TEXT.TXT")
However, when I try to package my program using Maven, I get a JAR in which all class and resources files are present in the same folder; my program stops working since it cannot find the file anymore.
Any help on how to deal with this problem? I`d prefer a situation in which my program works in eclipse and as a JAR, but as a JAR only would be alright as well.
You can use ClassLoader.getResourceAsStream to load it from the classpath (or getResource to get the URL of the file).
Thread.currentThread().getContextClassLoader().getResource("TEXT.TXT")
This works as long as src/main/resources is on the classpath in eclipse. (The maven eclipse plugin includes it by default.) The file has to be in the jar file to work outside of eclipse.
Nice suggestions, this works perfect in eclipse itself: the correct location of the file is returned and I can use the file to do whatever I like.
When opening the program as a jar, there is still a problem. The getResource method returns a location that looks like the right one:
/something/something/something/something/workspace/program/target/program-0.0.1.jar!/TEXT.TXT.
However, when I convert this url to a string, use that string to create a file object and use this file object in my program, I get the following error:
java.io.FileNotFoundException: file:/something/something/something/something/workspace/program/target/program-0.0.1.jar!/TEXT.TXT (No such file or directory)
So, the getResource method does find the file, but the program somehow can't use it..

Files not extracted from .jar file when run

I have updated my ant build.xml file to include a new file and a new folder. After creating the .jar I check if they exist in the jar by 'unzip\extract', and they are there.
But when executing the .jar neither the folder or the file gets extracted.
Am I missing a step?
Look into getResourceAsStream. It'll keep you from having to extract the files from the jar file. Unless that's your goal.
Your application should be able to use the file directly from within the jar, no need for extracting it. Or do you mean something else?
Are you doing something specific to extract the jar file? I ask because normally jar files are not extracted when executing them.
If you run "java -jar myJar.jar" or "java -cp myJar.jar com.example.MyMainClass" the jar files that is referenced will not be extracted. Java will load your classes and resources directly from the jar file without extracting it.
If you wrap your application up using One-JAR, you can specify an attribute in the Manifest file to extract files that you want (See the One-Jar-Expand manifest attribute).
As a bonus, you will also be able to wrap any dependent libraries along with your code, creating a single distributable jar.

Categories