如何在java中执行shell脚本?

2023-03-17 00:36:02 4

通过CommandHelper.execute方法可以执行命令。以下为该类实现的代码:

package javaapplication3;

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;

public class CommandHelper {

//默认超时时间,以毫秒为单位 public static int DEFAULT_TIMEOUT;

public static final int DEFAULT_INTERVAL = 1000;

public static long START;

//执行命令并返回结果 public static CommandResult exec(String command) throws IOException, InterruptedException { Process process = Runtime.getRuntime().exec(command); //执行命令 CommandResult commandResult = wait(process); //等待命令执行完成并获取结果 if (process != null) { process.destroy(); //销毁进程 } return commandResult; }

//判断是否已经超时 private static boolean isOverTime() { return System.currentTimeMillis() - START >= DEFAULT_TIMEOUT; }

//等待命令执行完成并获取结果 private static CommandResult wait(Process process) throws InterruptedException, IOException { BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream())); String line = ""; String result = ""; String errorResult = ""; while ((line = input.readLine()) != null || (errorResult = error.readLine()) != null) { if (line != null) { result += line + " "; } if (errorResult != null) { errorResult += errorResult + " "; } Thread.sleep(DEFAULT_INTERVAL); //等待一段时间再继续读取 if (isOverTime()) { //如果已经超时则直接返回结果 return new CommandResult(false, result, errorResult, -1); } } int exitValue = process.waitFor(); //获取进程退出值 return new CommandResult(true, result, errorResult, exitValue); }

}

该类中的exec方法可以执行命令并获取结果,若需要可以设置超时时间。执行完成后会返回一个CommandResult对象,其中包含了命令执行的结果。

爱网站

Linux、centOS、Ubuntu、Windows操作系统下的ECS云服务器、vps虚拟空间、建站主机到期停止异常等状态监测,宝塔面板Bt、小皮面板PHPStudy、IIS、Apache、Nginx、XAMPP、wamp建站环境意外故障监测,php+MySql、asp、java、html等建站程序运行故障监测,域名状态、SSL证书状态监测,网站301、302、404、500错误代码及网站无法访问通知提醒,全国多节点测试网站速度及网络攻击!

网站服务

扫一扫,关注我们

桂ICP备2022009721号-1