linux下JAVA调用shell脚本

5 篇文章 0 订阅
2 篇文章 0 订阅

JAVA调用shell脚本时,如果有大量输出,则用Runtime.exec()方法会很慢,这时应该用ProcessBuilder.start() 方法。搞了一晚上,苍了个天!具体参考原文:https://www.cnblogs.com/qingwen/p/5161166.html


阅读目录


Methods

ProcessBuilder.start() 和 Runtime.exec() 方法都被用来创建一个操作系统进程(执行命令行操作),并返回 Process 子类的一个实例,该实例可用来控制进程状态并获得相关信息。 

     Process process = Runtime.getRuntime().exec("C:\DoStuff.exe -arg1 -arg2");
  • The ProcessBuilder constructor takes a (varargs) array of strings. The first string is the command name and the rest of them are the arguments.
ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe", "-arg1", "-arg2");
//or alternatively
List<String> params = java.util.Arrays.asList("C:\DoStuff.exe", "-arg1", "-arg2");
ProcessBuilder b = new ProcessBuilder(params);
Process process = builder.start()

Examples 

复制代码
def execute = { context =>
      val command = shell(context)
      var result:Try[String]  = null
      var process:Process = null
      try {
        val builder = new ProcessBuilder(scala.collection.JavaConversions.seqAsJavaList(command))
        builder.redirectOutput(ProcessBuilder.Redirect.INHERIT)
        builder.redirectError(ProcessBuilder.Redirect.INHERIT)
        process = builder.start()
        process.waitFor()
        val exitCode = process.exitValue()
        if(exitCode != 0 ) {
          result = Failure(new IllegalMonitorStateException(s"Exit code of process is not zero, but: $exitCode"))
        }else {
          result = Success(s"Successfully executed command $command")
        }
      }catch{
        case e: Exception => result = Failure(e)
      } finally {
        if(process!=null) {
          process.destroy()
        }
      }
      result
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值