JAVA执行cmd命令方法

 

 

package com.cmd;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Test {

    /**
     * 调用方法
     * @param cmd cmd命令
     * @return
     */
    public static String exec(String cmd) {
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(cmd);
            InputStream es = proc.getErrorStream();
            String line;
            BufferedReader br;
            br = new BufferedReader(new InputStreamReader(es, "GBK"));
            StringBuffer buffer=new StringBuffer();
            while ((line = br.readLine()) != null) {
                buffer.append(line+"\n");
            }
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(exec("java -version"));
    }
}

 

posted @ 2020-06-12 23:57  yvioo  阅读(1934)  评论(0编辑  收藏  举报