本文主要介绍Java中,使用ProcessBuilder通过编码方式后台调用系统命令(ping)的方法,以及使用的示例代码。

1、Linux和Windows使用示例代码

bash -c "cmd string": 用-c 是bash 会从第一个非选项参数后面的字符串中读取命令,如果字符串有多个空格,第一个空格前面的字符串是要执行的命令,也就是$0, 后面的是参数,即$1, $2...。

bash xxx.sh:bash 会在当前目录去寻找xxx.sh,如果找到直接运行,找不到则按照环境变量$PATH的指定路径,按顺序去找,如果找到则执行,找不到则报错。

1) Linux

ProcessBuilder processBuilder = new ProcessBuilder();
//执行windows命令
processBuilder.command("bash", "-c", "ls /home/cjavapy/");
// 执行shell脚本
processBuilder.command("path/to/hello.sh");

2) Windows

// 执行linux命令
processBuilder.command("cmd.exe", "/c", "dir C:\\Users\\cjavapy");
// 执行bat脚本
processBuilder.command("C:\\Users\\cjavapy\\getip.bat");
Process process = processBuilder.start();

2、执行ping命令

package com.cjavapy.process;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ProcessBuilderExample1 {
    public static void main(String[] args) {
        ProcessBuilder processBuilder = new ProcessBuilder();
        // 在Windows上运行这个命令,cmd, /c 参数是在运行后终止
        processBuilder.command("cmd.exe", "/c", "ping -n 3 baidu.com");
       // 在Linux上运行
       //processBuilder.command("bash", "-c", "ping  baidu.com");
        try {
            Process process = processBuilder.start();
			// blocked :(
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int exitCode = process.waitFor();
            System.out.println("\nExited with error code : " + exitCode);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

或者

package com.cjavapy.process;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;
public class ProcessBuilderExample2 {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        ProcessBuilder processBuilder = new ProcessBuilder();
        //在Windows上运行这个命令,cmd, /c 参数是在运行后终止
        processBuilder.command("cmd.exe", "/c", "ping -n 3 google.com"); 
        //在Linux上运行
        //processBuilder.command("bash", "-c", "ping  baidu.com");
        try {
            Process process = processBuilder.start();
            System.out.println("process ping...");
            ProcessReadTask task = new ProcessReadTask(process.getInputStream());
            Future<list<string>> future = pool.submit(task);
            // no block, can do other tasks here
            System.out.println("process task1...");
            System.out.println("process task2...");
            List<string> result = future.get(5, TimeUnit.SECONDS);
            for (String s : result) {
                System.out.println(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            pool.shutdown();
        }
    }
    private static class ProcessReadTask implements Callable<list<string>> {
        private InputStream inputStream;
        public ProcessReadTask(InputStream inputStream) {
            this.inputStream = inputStream;
        }
        @Override
        public List<string> call() {
            return new BufferedReader(new InputStreamReader(inputStream))
				.lines()
				.collect(Collectors.toList());
        }
    }
}

3、改变目录且显示目录中内容

package com.cjavapy.process;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class ProcessBuilderExample3 {
    public static void main(String[] args) {
        ProcessBuilder processBuilder = new ProcessBuilder();
        //windows
        //processBuilder.command("cmd.exe", "/c", "dir");
        //processBuilder.directory(new File("C:\\users"));
        //linux
        processBuilder.command("bash", "-c", "ls -al");
        processBuilder.directory(new File("/home"));
        try {
            Process process = processBuilder.start();
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int exitCode = process.waitFor();
            System.out.println("\nExited with error code : " + exitCode);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

相关文档:

Java 通过ProcessBuilder或Runtime.exec()调用(cmd/sh)系统命令方法代码
execute-shell-command-from-java