Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a system independent classpath

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?

like image 310
michas Avatar asked Aug 29 '14 08:08

michas


1 Answers

  • 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.

like image 129
aioobe Avatar answered Sep 30 '22 00:09

aioobe