码迷,mamicode.com
首页 > 编程语言 > 详细

java操作CMD命令

时间:2017-09-05 18:57:02      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:run   nal   writer   doc   buffer   sys   print   cpi   close   

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

public class CMD命令 {
    public static void main(String[] args) {
        docmd();
    }

    static void docmd() {
        String[] command = { "cmd", };
        Process p = null;
        try {
            p = Runtime.getRuntime().exec(command);
            new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
            new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
            PrintWriter stdin = new PrintWriter(p.getOutputStream());
            /** 以下可以输入自己想输入的cmd命令 */
            stdin.println("java -version");
            stdin.close();
        } catch (Exception e) {
            throw new RuntimeException("编译出现错误:" + e.getMessage());
        }
    }
}

class SyncPipe implements Runnable {

    private final OutputStream ostrm_;
    private final InputStream istrm_;
    public SyncPipe(InputStream istrm, OutputStream ostrm) {
        istrm_ = istrm;
        ostrm_ = ostrm;
    }

    public void run() {
        try {
            final byte[] buffer = new byte[1024];
            for (int length = 0; (length = istrm_.read(buffer)) != -1;) {
                ostrm_.write(buffer, 0, length);
            }
        } catch (Exception e) {
            throw new RuntimeException("处理命令出现错误:" + e.getMessage());
        }
    }
}

 

java操作CMD命令

标签:run   nal   writer   doc   buffer   sys   print   cpi   close   

原文地址:http://www.cnblogs.com/chenglc/p/7479914.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!