Java Runtime.exec()的使用

Sun的doc里其实说明还有其他的用法:

exec(String[] cmdarray, String[] envp, File dir)

Executes the specified command and arguments in a separate process with the specified environment and working directory.

那个dir就是调用的程序的工作目录,这句其实还是很有用的。

Windows下调用程序

Process proc =Runtime.getRuntime().exec("exefile");

Linux下调用程序就要改成下面的格式

Process proc =Runtime.getRuntime().exec("./exefile");

Windows下调用系统命令

String [] cmd={"cmd","/C","copy exe1 exe2"}; 
Process proc =Runtime.getRuntime().exec(cmd);

Linux下调用系统命令就要改成下面的格式

String [] cmd={"/bin/sh","-c","ln -s exe1 exe2"}; 
Process proc =Runtime.getRuntime().exec(cmd);

Windows下调用系统命令并弹出命令行窗口

String [] cmd={"cmd","/C","start copy exe1 exe2"}; 
Process proc =Runtime.getRuntime().exec(cmd);

Linux下调用系统命令并弹出终端窗口就要改成下面的格式

String [] cmd={"/bin/sh","-c","xterm -e ln -s exe1 exe2"};
Process proc =Runtime.getRuntime().exec(cmd);

还有要设置调用程序的工作目录就要

Process proc =Runtime.getRuntime().exec("exeflie",null, new File("workpath"));

最后,封装工具类

package com.xxx.util;

import org.apache.commons.lang3.StringUtils;

import java.io.*;

/**
 * @author yc
 * @date 2019/5/15
 */
public class ShellUtil {

    /**
     * shell命令
     *
     * @param cmd       命令
     * @param directory 工作目录
     * @throws Exception return errorMSG
     */
    public synchronized static String exec(String cmd, File directory) throws Exception {
        Runtime runtime = Runtime.getRuntime();

        StringBuffer errLog = new StringBuffer();

        String[] param = new String[3];

        String osName = System.getProperty("os.name");
        if (osName.startsWith("Mac OS")) {
            // 苹果
        } else if (osName.startsWith("Windows")) {
            // windows
            param[0] = "cmd";
            param[1] = "/C";
            param[2] = "GBK";
        } else {
            // unix or linux
            param[0] = "/bin/sh";
            param[1] = "-c";
            param[2] = "UTF-8";
        }

        Process process = runtime.exec(new String[]{param[0], param[1], cmd}, null, directory);
        InputStream inputStream = process.getInputStream();
        BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(inputStream, param[2]));
        InputStream errorStream = process.getErrorStream();
        BufferedReader errorStreamReader = new BufferedReader(new InputStreamReader(errorStream, param[2]));

        Thread std = new Thread(() -> {
            try {
                String line = null;
                while ((line = inputStreamReader.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (Exception e) {
                errLog.append(e.getMessage());
            }
        });
        Thread err = new Thread(() -> {
            try {
                String line = null;
                while ((line = errorStreamReader.readLine()) != null) {
                    errLog.append(line);
                }
            } catch (Exception e) {
                errLog.append(e.getMessage());
            }

        });
        std.start();
        err.start();
        std.join();
        err.join();
        process.waitFor();

        return errLog.toString();
    }
}

 

posted @ 2018-11-16 11:54  量化未来  阅读(2478)  评论(0编辑  收藏  举报