使用scala.sys.process包和系统交互

39 篇文章 0 订阅
2 篇文章 0 订阅
在Java中我们可以使用Runtime.getRuntime().exec();来和系统交互。这个API过于底层,exec返回一个代表进程的对象,然后从中读取执行结果或者错误信息。并且如果不关心进程的输出,而没有把输入结果重定向到/dev/null,超过输出结果的buffer就会阻塞。
scala.sys.process提供了shell的和系统交互的DSL,包括执行命令、逻辑操作、重定向、管道等操作。
使用!来执行外部命令:

"find project -name *.jar" !

如果没有参数,直接输出到标准输出或者标准错误输出
你可以传递Logger参数给!

"find project -name *.jar" ! log

如果想保存到变量中:

val result = "find project -name *.jar" !!

使用逻辑操作#&&,#||
cmd1 #&& cmd2
cmd1 #|| cmd2
使用管道:
cmd1 #| cmd2
例子:

"find src -name *.scala -exec grep null {} ;" #| "xargs test -z" #&& "echo null-free" #|| "echo null detected" !

使用重定向:
scala的重定向不仅可以从定向普通的文件,还可以把网络上的文件进行重定向到本地:
a #< url or url #> a
例子:

url("http://fuliang.iteye.com") #> file("blog.html") !
//或者
file("blog.html") #< url("http://fuliang.iteye.com") !

文件:
a #< file or file #> a
a可以是一个文件或者一个命令,比如:

file("blog.html") #> file("fuliang_blog.html") !
//或者
file("fuliang_blog.html") #< file("blog.html") !

还可以使用 #>> #<<追加操作:
a #>> file or file #<<

url("http://fuliang.iteye.com") #> "grep -i ruby" #>> file("Ruby") !
//或者
file("Ruby") #<< ( "grep ruby" #< url(http://fuliang.iteye.com") ) !

使用cat:

val spde = url("http://technically.us/spde/About")
val dispatch = url("http://databinder.net/dispatch/About")
val build = file("project/build.properties")
cat(spde, dispatch, build) #| "grep -i scala" !


当然这一切的操作时通过字符串操作和执行命令的!、!!操作符完成的。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值