java中执行cmd命令_如何通过Java执行cmd命令

小编典典

我在forums.oracle.com中找到了

允许重用进程以在Windows中执行多个命令:http : //kr.forums.oracle.com/forums/thread.jspa?messageID=9250051

你需要类似的东西

String[] command =

{

"cmd",

};

Process 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());

stdin.println("dir c:\\ /A /Q");

// write any other commands you want here

stdin.close();

int returnCode = p.waitFor();

System.out.println("Return code = " + returnCode);

SyncPipe类别:

class SyncPipe implements Runnable

{

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)

{

e.printStackTrace();

}

}

private final OutputStream ostrm_;

private final InputStream istrm_;

}

2020-03-04

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值