Java Runtime类执行Shell命令

在做项目的过程中,有时候使用命令行会更加的简易。话不多说贴代码。

    /**
     * 通过命令解析文件内的内容
     *
     * @param cmd 命令
     */
    public void execLinuxCmd(String cmd) {
        if (CommonUtils.isNullOrEmpty(cmd)) {
            return;
        }
        try {
            Process pro = Runtime.getRuntime().exec(cmd);
            pro.waitFor();
            InputStream in = pro.getInputStream();
            BufferedReader read = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = read.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

        通过传入cmd命令调用改方法,实际上是通过Runtime这个类,应用程序本身可以与其所在的环境进行通信。

        通过该getRuntime()方法提取与我们的应用程序关联的运行时,我们可以使用该exec()方法直接执行命令或运行.bat/.sh文件。

/* 执行包含在command单独进程中的命令。 */
public Process exec(String command)

         在后面执行的时候遇到了一个问题,当需要在命令中先进入文件所在目录再进行执行,一开始使用这个方法通过&&的方式连接两条命令,如下

cd /d C:\Users\xxx&&go build xxx.go

        运行后程序报错

java.io.IOException: Cannot run program "'cd": CreateProcess error=2, 系统找不到指定的文件。
	at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
	at java.lang.Runtime.exec(Runtime.java:620)
	at java.lang.Runtime.exec(Runtime.java:450)
	at java.lang.Runtime.exec(Runtime.java:347)
	at com.wiiot.api.utils.FileUtil.execLinuxCmd(FileUtil.java:162)

        后来想到了exec()方法的另一个重载

/* command从dir目录中执行带有指定环境变量的。*/
public Process exec(String command, String[] envp, File dir)

        于是又进行了一次封装

     /**
     * 在指定目录下执行命令
     * @param cmd
     * @param dir
     */
    public void execCmdWithDir(String cmd,String dir) {
        if (CommonUtils.isNullOrEmpty(cmd)||CommonUtils.isNullOrEmpty(dir)) {
            return;
        }
        try {
            Process pro = Runtime.getRuntime().exec(cmd,null,new File(dir));
            pro.waitFor();
            InputStream in = pro.getInputStream();
            BufferedReader read = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = read.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

Tips:顺便记录一下通过System类获取操作系统名称的过程

System.getProperty("os.name")

这里获取操作系统的名称是为了用于判断程序运行时所处的环境再去执行对应的命令行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以通过Runtime和ProcessBuilder来调用Shell命令和脚本。下面是一个简单的示例: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ShellCommand { public static void main(String[] args) { try { // 执行Shell命令 Process process = Runtime.getRuntime().exec("ls -al"); // 读取Shell命令的输出 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待Shell命令执行完毕 int exitCode = process.waitFor(); System.out.println("Shell命令执行完毕,退出码为:" + exitCode); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } ``` 在上述示例中,我们通过Runtimeexec()方法执行了一个Shell命令,然后通过Process的getInputStream()方法获取了Shell命令的输出流,并通过BufferedReader逐行读取了输出内容。最后,我们通过Process的waitFor()方法等待Shell命令执行完毕,并获取了Shell命令的退出码。 似地,我们也可以使用ProcessBuilder执行Shell脚本。以下是一个示例: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class ShellScript { public static void main(String[] args) { try { // 执行Shell脚本 ProcessBuilder builder = new ProcessBuilder(Arrays.asList("/bin/bash", "-c", "./test.sh")); Process process = builder.start(); // 读取Shell脚本的输出 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待Shell脚本执行完毕 int exitCode = process.waitFor(); System.out.println("Shell脚本执行完毕,退出码为:" + exitCode); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } ``` 在上述示例中,我们使用ProcessBuilder创建了一个Shell进程,并指定了要执行Shell脚本。然后通过Process的getInputStream()方法获取了Shell脚本的输出流,并通过BufferedReader逐行读取了输出内容。最后,我们通过Process的waitFor()方法等待Shell脚本执行完毕,并获取了Shell脚本的退出码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值