这篇文章主要讲解了Java如何执行cmd命令,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
一般java在执行CMD命令时,通常是使用Runtime.getRuntime.exec(command)来执行的,这个方法有两种细节要注意:
1.一般执行方法,代码如下,这种方法有时执行exe时会卡在那里。
//一般的执行方法,有时执行exe会卡在那 stmt要执行的命令
public static void executive(String stmt) throws IOException, InterruptedException {
Runtime runtime = Runtime.getRuntime(); //获取Runtime实例
//执行命令
try {
String[] command = {"cmd", "/c", stmt};
Process process = runtime.exec(command);
// 标准输入流(必须写在 waitFor 之前)
String inStr = consumeInputStream(process.getInputStream());
// 标准错误流(必须写在 waitFor 之前)
String errStr = consumeInputStream(process.getErrorStream());
new ProcessClearStream(process.getInputStream(), "INFO").start();
new ProcessClearStream(process.getErrorStream(), "ERROR").start();
int proc = process.waitFor();
InputStream errorStream = process.getErrorStream(); //若有错误信息则输出
if (proc == 0) {
System.out.println("执行成功");
} else {
System.out.println("执行失败" + errStr);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
/**
* 消费inputstream,并返回
*/
public static String consumeInputStream(InputStream is) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(is,"GBK"));
String s;
StringBuilder sb = new StringBuilder();
while ((s = br.readLine()) != null) {
System.out.println(s);
sb.append(s);
}
return sb.toString();
}
2.第二种方法是先生成一个缓存文件,用来缓存执行过程中输出的信息,这样在执行命令的时候不会卡。代码如下:
//这个方法比第一个好,执行时不会卡 stmt要执行的命令
public static void aaa(String stam){
BufferedReader br = null;
try {
File file = new File("D:\\daemonTmp");
File tmpFile = new File("D:\\daemonTmp\\temp.tmp");//新建一个用来存储结果的缓存文件
if (!file.exists()){
file.mkdirs();
}
if(!tmpFile.exists()) {
tmpFile.createNewFile();
}
ProcessBuilder pb = new ProcessBuilder().command("cmd.exe", "/c", stam).inheritIO();
pb.redirectErrorStream(true);//这里是把控制台中的红字变成了黑字,用通常的方法其实获取不到,控制台的结果是pb.start()方法内部输出的。
pb.redirectOutput(tmpFile);//把执行结果输出。
pb.start().waitFor();//等待语句执行完成,否则可能会读不到结果。
InputStream in = new FileInputStream(tmpFile);
br= new BufferedReader(new InputStreamReader(in));
String line = null;
while((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
br = null;
tmpFile.delete();//卸磨杀驴。
System.out.println("执行完成");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
看完上述内容,是不是对Java如何执行cmd命令有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。