I need to run a java command with a custom classpath.
On Windows I need to type:
java -cp foo;bar
On Linux I need to type:
java -cp foo:bar
We currently have a .bat file containing the first version and a .sh file containing the second version. This works fine most of the time, but fails for git-bash on Windows, which needs a shell script with a semicolon delimiter.
Is there any system independent way to write such a classpath?
I would think of something like
java -cp foo -cp bar
but this does not this way.
Currently the only way I see is having some shell logic determining the OS and generating the correct command line from that.
Is there an easier way to do this the java way?
Option 1: If you don't mind creating a jar before running, you could specify the classpath in a manifest file. Those paths are space-separated. (See Adding Classes to the JAR File's Classpath)
Option 2 Add code for detecting OS using for instance uname
. Then do either SEP=\;
or SEP=:
and use path${SEP}path
. (See for instance How to check if running in Cygwin, Mac or Linux?)
Option 3: Grep the java help output to see what separator character java expects:
SEP=$(java -h |& grep "A [:;] separated" | grep -o "[:;]")
Option 4: If you have the JDK installed, you can print the File.pathSeparator
:
echo "interface C { static void main(String[] a) { System.out.print(java.io.File.pathSeparator); }}" > C.java
javac C.java
java C
rm C.{java,class}
Note: Only the path separators, i.e. ;
vs :
, are platform specific. Forward slashes (i.e. some/class/path
) work fine on all systems for separating directories.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With