BAT file to create Java CLASSPATH

2019-01-16 05:45发布

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条回答
淡お忘
2楼-- · 2019-01-16 06:26

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.

查看更多
SAY GOODBYE
3楼-- · 2019-01-16 06:26

Is there an easier way to do this?

Yes;

Since version 6, you can use class path wildcards.

javac -cp .;../lib/* yourJavaCodeDir/YourJavaFile.java

See also this related Q&A.

查看更多
乱世女痞
4楼-- · 2019-01-16 06:27

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.

查看更多
时光不老,我们不散
5楼-- · 2019-01-16 06:29

An option to make things portable is to set the classpath relative to the location of the batch file itself.

In Windows (assuming Java 6+, classes in ./bin, jars in ./lib):

@java -classpath %~dp0/bin;%~dp0/lib/* ClassName %1
查看更多
聊天终结者
6楼-- · 2019-01-16 06:31

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.

查看更多
趁早两清
7楼-- · 2019-01-16 06:38

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.

查看更多
登录 后发表回答