Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an executable .jar file be called without having to use its full path?

I have a .jar file that I would like to be able to call without having to use a full file path to its location.

For example, if the .jar file is located at: /some/path/to/thearchive.jar

I'd like to be able to run it with:

java -jar thearchive.jar

instead of:

java -jar /some/path/to/thearchive.jar

when I'm elsewhere in the directory tree. In my specific case, I'm running a Mac with OS X 10.5.7 installed. Java version "1.5.0_16". I tried adding "/some/path/to" to PATH, JAVA_HOME and CLASSPATH, but that didn't work.

So, how do I setup to run a .jar from the command line without having to use its full path?

UPDATE: Another item to deal with would be arguments. For example:

java -jar /some/path/to/thearchive.jar arg1 arg2

This can have an effect on the way the question is dealt with as mentioned in the answers below.

like image 783
Alan W. Smith Avatar asked Jun 01 '09 20:06

Alan W. Smith


People also ask

What is the difference between jar and executable jar?

FYI: In simple terms, the difference between a JAR file and a Runnable JAR is that while a JAR file is a Java application which requires a command line to run, a runnable JAR file can be directly executed by double clicking it.

What happens when a JAR file is executed?

Most JAR files are simply containers for data that another program needs to run with Java; therefore you cannot run these files and nothing will happen when you double-click them. Similarly, most executable JAR files are downloaded as installation files to install applications or programs.

Does a JAR file need to be executable?

Java Runtime Environment (To Run The file) If you want to run the JAR file, you will need the Java Runtime Environment. If you have the Java Runtime Environment, then all you need to do is to double click on the file name. But it will only work if that particular file is executable.

Can a JAR file run anywhere?

Spring Boot can take your application code, combine it with an embedded JEE Application Server (like Tomcat, which you never even see), and package it all up together into an executable JAR file. This JAR file will run anywhere there's a compatible JVM.


2 Answers

You can add a variable to hold the directory:

export JARDIR=/some/path/to
java -jar $JARDIR/thearchive.jar

I'm not sure you can do it from environment variables implicitly.

like image 54
brabster Avatar answered Oct 27 '22 09:10

brabster


No you can't.

Running a jar with -jar does not involve any kind of classpath mechanism since the jar file is the classpath.

Alternatively use a shell alias to launch the jar or a small script file.

like image 37
Robert Munteanu Avatar answered Oct 27 '22 09:10

Robert Munteanu