运行具有外部依赖项的Scala脚本

Lan*_*ali 5 java bash scripting jvm scala

我在/Users/joe/.scala/lib下面有以下jar:

commons-codec-1.4.jar       
httpclient-4.1.1.jar        
httpcore-4.1.jar
commons-logging-1.1.1.jar   
httpclient-cache-4.1.1.jar  
httpmime-4.1.1.jar
Run Code Online (Sandbox Code Playgroud)

下面是我用scala编写的test.sh.

#!/bin/sh -v
L=`cd /Users/joe/.scala/lib;pwd`
cp=`echo $L/*.jar|sed 's/ /:/g'`
echo $cp
exec scala -classpath $cp $0 $@
!#
println(new org.apache.commons.httpclient.HttpClient())
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

$ ./test.sh 
#!/bin/sh -v
L=`cd /Users/joe/.scala/lib;pwd`
cd /Users/joe/.scala/lib;pwd
cp=`echo $L/*.jar|sed 's/ /:/g'`
echo $L/*.jar|sed 's/ /:/g'
echo $cp
/Users/joe/.scala/lib/commons-codec-1.4.jar:/Users/joe/.scala/lib/commons-logging-1.1.1.jar:/Users/joe/.scala/lib/httpclient-4.1.1.jar:/Users/joe/.scala/lib/httpclient-cache-4.1.1.jar:/Users/joe/.scala/lib/httpcore-4.1.jar:/Users/joe/.scala/lib/httpmime-4.1.1.jar
exec scala -classpath $cp $0 $@
/Users/joe/Desktop/scala/./test.sh:7: error: object httpclient is not a member of package org.apache.commons
println(new org.apache.commons.httpclient.HttpClient())
                               ^
one error found
Run Code Online (Sandbox Code Playgroud)

但是,没有任何类路径依赖关系的简单工作虽然:hello.sh

#!/bin/sh
exec scala "$0" "$@"
!#

println(new java.util.Date())
Run Code Online (Sandbox Code Playgroud)

知道我在第一个例子中做错了什么吗?或者,在使用scala脚本时,设置类路径依赖关系的最佳方法是什么?

Dan*_*ral 10

我不打算回答你的问题,但你可能会对此感兴趣.

假设您下载并安装SBT(版本0.10.0或更高版本),并创建一个名为" scalas " 的shell脚本:

java -Dsbt.main.class=sbt.ScriptMain \
     -Dsbt.boot.directory=/home/user/.sbt/boot \
     -jar sbt-launch.jar "$@"
Run Code Online (Sandbox Code Playgroud)

然后你像这样写你的脚本:

#!/usr/bin/env scalas
!#

/***
scalaVersion := "2.9.1"

libraryDependencies ++= Seq(
  "commons-codec" % "commons-codec" % "1.4", 
  "org.apache.httpcomponents" % "httpclient" % "4.1.1",
  "org.apache.httpcomponents" % "httpcore" % "4.1",
  "commons-logging" % "commons-logging" % "1.1.1",
  "org.apache.httpcomponents" % "httpclient-cache" % "4.1.1", 
  "org.apache.httpcomponents" % "httpmime" % "4.1.1"
)
*/

println(new org.apache.http.client.DefaultHttpClient())
Run Code Online (Sandbox Code Playgroud)


Don*_*oby 4

我认为 4.1.1 中的类是 org.apache.http.client.HttpClient 而不是 org.apache.commons.httpclient,它是一个接口。所以你可能想要

new org.apache.http.client.DefaultHttpClient()
Run Code Online (Sandbox Code Playgroud)

代替

new org.apache.commons.httpclient.HttpClient()
Run Code Online (Sandbox Code Playgroud)

早期版本可能有所不同。