您的位置:首页 > 编程语言 > Java开发

Java操作Cmd命令

2015-09-24 10:19 246 查看
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
* 日期 : 2015年9月14日<br>
* 项目 : Test<br>
* 功能 : <br>
*/
public class Cmd {
public static void main(String[] args) {
BufferedReader br = null;
try {
while (true) {
//运行多级cmd可以用 && 让命令在一行中运行
List<String> list = run("cmd.exe /c d: && cd D:\\project && gulp phone");
if (list == null || list.size() < 1) {
return;
}
String str = list.get(1);
String[] arr = str.split("'");
str = arr[1];
if (arr.length != 2) {
return;
}
list = run("cmd.exe /c d: && cd D:\\project && npm install " + str);
Thread.sleep(1000);
}

} catch (Exception e) {
e.printStackTrace();
} finally {

if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

/**
* Description :
*
* @return
* @throws IOException
*/
private static List<String> run(String cmd) throws IOException {
BufferedReader br;
//运行cmd
Process p = Runtime.getRuntime().exec(cmd);
//获得输出流
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
List<String> list = new ArrayList<String>();
String line = null;
//读取内容
while ((line = br.readLine()) != null) {
System.out.println(line);
list.add(line);
}
//打印异常输出流
if (p.getErrorStream() != null) {
br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line2 = null;
while ((line2 = br.readLine()) != null) {
System.out.println(line2);
list.add(line2);
}
}
return list;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java cmd