AndreaNobili
AndreaNobili

Reputation: 42967

Why I obtain this "Unable to access jarfile" error when I try to execute my jar?

I have the following problem trying to execute a jar file (created from my project) into the Windows shell (the DOS prompt).

I have a file named Main.jar. If I unzip this file it contains a mainPkg folder (that is the name of the package containing the Main class that itself contains the main() method).

So into the mainPkg folder there is the Main.class file that contains the main() method.

Ok so, from the shell, I go into the directory that contains the Main.jar and I perform:

C:\Projects\edi-sta\build\jar>java -jar mainPkg.Main.jar
Error: Unable to access jarfile mainPkg.Main.jar

But as you can see I obtain the Unable to access jarfile mainPkg.Main.jar. Why? What am I missing? How can I solve this issue and execute my Main.jar file?

Upvotes: 0

Views: 28473

Answers (2)

Arkantos
Arkantos

Reputation: 6608

Basically you've two types of JARs

  • Normal JAR - to package your classes into a single archive
  • Runnable JAR - This is similar to Normal jar except that you can run this with java -jar command like this java -jar RunnableMain.jar. In this one we already configure the class having main(),so no need to pass the class name in jar command

Assuming that yours is a normal JAR, you can execute your class of interest like this

C:\Users\arkantos\work>java -classpath C:\Project\Main.jar mainPkg.Main

Notice that i've mentioned the absolute path of the JAR to add it to classpath, because I'm in a different directory, if not you can cd to that dir containing your Main.jar and then invoke your Main class like this

C:\Project>java -classpath Main.jar mainPkg.Main

Here Main.jar is inside Project directory so no need to give absolute path

Upvotes: 3

K Erlandsson
K Erlandsson

Reputation: 13696

The syntax for executing a class containing a main method in a jar is:

java -classpath <jarFile> <class>

In your case:

java -classpath Main.jar mainPkg.Main

If you want to execute the jar using java -jar you must create an executable jar file. That can be done in different ways depending on which build tools you use.

Upvotes: 3

Related Questions