Java编程思想:进程控制

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

public class Test {
    public static void main(String[] args) {
        OSExecuteDemo.test();
    }
}

/*
    程序运行过程中将可能产生两种错误:
        1.普通的导致异常的错误
        2.进程自身的执行的过程中产生的错误
 */
class OSExecuteException extends RuntimeException {
    public OSExecuteException(String why) {
        super(why);
    }
}

/*
    要想运行一个程序,需要向OSExecute.Command()传递一个command字符串,它与
    在控制台上运行该程序所键入的命令相同。这个命令被传递给
    java.lang.ProcessBuilder构造器(它要求这个命令作为一个String对象序列被
    传递),然后所产生的ProcessBuilder对象被启动。
 */
class OSExecute {
    public static void command(String command) {
        boolean err = false;
        try{
            Process process = new ProcessBuilder(command.split(" ")).start();

            //输出程序运行的结果
            BufferedReader results = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));
            String str;
            while ((str = results.readLine()) != null) {
                System.out.println(str);
                //System.out.println(new String(str.getBytes("GBK"),"utf-8"));
            }

            //输出程序运行中产生的错误
            BufferedReader errors = new BufferedReader(
                    new InputStreamReader(process.getErrorStream()));
            while ((str = errors.readLine()) != null) {
                System.out.println(str);
                err=true;
            }
        } catch (Exception e) {
            if(!command.startsWith("CMD /C")){
                command("CMD /C " +command);
            }else {
                throw  new RuntimeException();
            }
        }
        if(err){
            throw new OSExecuteException("Errors executeing "+command);
        }
    }
}

class OSExecuteDemo {
    public static void test() {
//        OSExecute.command("javap OSExecuteDemo");
        OSExecute.command("java");
    }
}

猜你喜欢

转载自www.cnblogs.com/junjie2019/p/10537871.html