简体   繁体   中英

Providing path relative to main class for classpaths when running from command line

I am trying to execute a compiled version of my program attachmentUploader.jar from the command line. This has a number of dependencies on various Java libraries, which I am planning to bundle up with the program and specify as part of the classpath. This package will be moved between environments, and will be executed using the Java runtime for that environment. Using absolute paths for my environment, the command looks like this:

"C:\Program Files\Java\jdk1.6.0_37bin\java" -cp "C:/Users/My Documents/jars/attachmentLoader.jar";"C:\Dev Tools\jxl.jar";"C:\Dev Tools\org.apache.commons.codec";"C:\More Dev Tools\java-json.jar" com.custom.test.postClient

I would like to amend all the classpath jar paths to be relative to where my main class is saved, but I read that relative paths in this situation would be relative to where the Java is executed from. In my case this could be anywhere, as it will depend on where this has been installed. Is there a straightforward way of getting round this?

Thanks all.

There are actually several ways:

  1. Make your jar file an executable jar file. That is done by adding a manifest file to the jar specifying what the main class is, and where the jar dependencies are located, relative to the location of the main jar file. The command to execute the program would then be java -jar path\\to\\jarfile.jar
  2. Use a wrapper executable or shell script, that uses the location of the script itself to compose the classpath. Such a script would depend on the system (Unix/Windows), but both platforms allow script files to know their own location, and thus to use that location as a basis for the location of jar files. An advantage of that technique is that it also allows passing system properties, memory options, etc. to the JVM.

I recommend you use a standard build tool such as gradle , which has an application plugin generating all those script files for you, for all platforms, and bundles the whole application into a zip or tar.gz file.

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