Running standalone Groovy scripts

总结:

用java运行groovy的两种方式:

1)只运行groovy脚本:

java -jar groovy-all.jar hello.groovy

2) groovy用到了java的jar包

java -cp groovy-all.jar;mylib.jar groovy.ui.GroovyMain hello.groovy



http://www.vasanth.in/2011/06/29/running-standalone-groovy-scripts/


Running standalone Groovy scripts

As I mentioned in my post Learning Groovy, I am writing Groovy scripts to automate some simple tasks. Now I want to share the scripts with others. I did not want them to install Groovy just to run the scripts. I had the groovy-all-1.8.0.jar, so I typed the following in the command prompt:

1
2
C:\temp >java -jar groovy-all-1.8.0.jar Hello.groovy
Hello

It worked. Simple. Now I tried to run my script that retrieved the XMLs from a database.

1
2
3
4
C:\work\FetchData >java -jar groovy-all-1.8.0.jar FetchData.groovy
Caught: java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at FetchData.fetch (FetchData.groovy:51 )
at FetchData.run (FetchData.groovy:3 )

Of course I need the driver jar in the classpath. So I added the sqljdbc.jar to the classpath.

1
2
3
4
C:\work\FetchData >java -cp sqljdbc.jar -jar groovy-all-1.8.0.jar FetchData.groovy
Caught: java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
        at FetchData.createCSV (FetchData.groovy:51 )
        at FetchData.run (FetchData.groovy:3 )

Looks like the script is run with a different classloader and the java classpath is not passed to it. I did some lazy googling but did not find the answer I was looking for. So I looked at how eclipse is doing it. Eclipse used GroovyStarter and GroovyMain to run scripts. Not knowing which to use, I just used GroovyMain:

1
2
C:\work\FetchData >java -cp lib/groovy-all-1.8.0.jar;lib/sqljdbc.jar groovy.ui.GroovyMain FetchData.groovy
Fetched Data !

It worked! I just added the command in a batch file to share the script.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值