BAT file to create Java CLASSPATH

Viewed 88597

I want to distribute a command-line application written in Java on Windows.

My application is distributed as a zip file, which has a lib directory entry which has the .jar files needed for invoking my main class. Currently, for Unix environments, I have a shell script which invokes the java command with a CLASSPATH created by appending all files in lib directory.

How do I write a .BAT file with similar functionality? What is the equivalent of find Unix command in Windows world?

10 Answers

You want to use the for loop in Batch script

 @echo off
 setLocal EnableDelayedExpansion
 set CLASSPATH="
 for /R ./lib %%a in (*.jar) do (
   set CLASSPATH=!CLASSPATH!;%%a
 )
 set CLASSPATH=!CLASSPATH!"
 echo !CLASSPATH!

This really helped me when I was looking for a batch script to iterate through all the files in a directory, it's about deleting files but it's very useful.

One-line batch script to delete empty directories

To be honest, use Jon's answer though, far better if all the files are in one directory, this might help you out at another time though.

Why would you use find? Presumably you know all the libraries your jar file needs ahead of time, so why not just list them?

Alternatively, you could always use -Djava.ext.dirs=lib and let it pick up everything that way.

A variation if you want the CLASSPATH setting to hold outside of the script and you didn't start the shell with /V, you can do something like this:

@echo off
FOR /R ./lib %%a in (*.jar) DO CALL :AddToPath %%a
ECHO %CLASSPATH%
GOTO :EOF

:AddToPath
SET CLASSPATH=%1;%CLASSPATH%
GOTO :EOF

Useful for setting up your environment when you are just playing around on the command line.

Sounds like an executable JAR could work for you. If you're distributing a ZIP with all the JARs your main routine needs, and you really execute it in a command shell, perhaps you could create an executable JAR with the Main-Class and Classpath defined in the manifest. All your users have to do is double click on the JAR and Bob's your uncle.

What I do when I release command-line JARs for Windows/Linux is to embed all the JAR libraries inside my JAR using the ANT command:

       <fileset dir="${module.classes.dir}"/>
       <zipfileset src="${endorsed.lib.dir}/myLibrary.jar"/>

In this way the libraries are melt together with your class files.

It is not the best way of binary reusability, but if the libraries are not so heavy, you have your application executed by simply calling java -jar myApp.jar in any OS.

You may use a bit different way if you use Maven to build your project. Application Assembler Maven Plugin is intended for creating Java apps launchers. This plug-in generate bat file launcher for you and put dependencies in specified folder. Optionally you launcher is able to register you application as a service\demon.

This is a topic about using it

This plug-in helps keeping you CM parts of your project DRY.

Related