【转】在批处理中加载某个目录所有的jar

 
我平常做服务器或者应用程序的时候喜欢把各种依赖包如log4j, jdbc, commons-lang等放到一个lib目录下,然后启动的时候将这些jar包设置到classpath上。以前我经常使用set classpath=log4j.jar;jdbc.jar;commons-lang.jar硬加载,但问题就是每新加入一个jar,就得改批处理一次,再就是每开发一个就得这么设置一次。很烦人,perl 创始人说,偷懒的程序员才是好程序员:),我需要一个通用的加载方式。

不管linux/windows或其它OS,都提供一个shell与kernel交互,并且shell都有一个类似的for内置commnd。

下面是linux bash的尝试
#!/usr/bin/sh

clspath
="bootstrap.jar"
for k in *.jar
do

 clspath
=$clspath:$PWD/$k
 echo 
"current jar is $k."
done
printf "classpath is %s" $clspath

工作的很好,于是在windows同样try了一下batch
@echo off

set clspath
=bootstrap.
jar
for %%j in (*.jar) do
 (
set clspath
=%clspath%;%cd%\%%j

echo current jar is 
%%j.
)
echo classpath is 
%clspath%

很奇怪的是最后的结果却是 classpath is bootstrap.jar;D:workflowingolibservlet-api.jar。很显然batch默认不支持变量迭代更改
google了一下,发现原因,稍微改一下:
 
 1@echo off
 2

 3set clspath=bootstrap.
jar
 4
setlocal enabledelayedexpansion
 5for %%j in (*.jar) do
 (
 6set clspath=!clspath!;%cd%\%%j

 7echo current jar is %%j.
 8)
 9echo classpath is %clspath%

10endlocal


对比一下,可以发现:

  1. 第4行加上了setlocal enabledelayedexpansion,即变量延迟展开。
  2. 第10行有一个endlocal,结束这个设置
  3. 第6行把%classpath%变成了!classpath!。

虽然目的达到了,还是要鄙视微软的dos batch,实在很弱,不知Powershell怎样。

参考资料:
   
setlocal

阅读(350) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~
评论热议
原文地址:https://www.cnblogs.com/black/p/5171902.html