//执行命令 Process process = Runtime.getRuntime().exec(cmd); //等待执行完毕 process.waitFor(); //执行结果,0是正常 int value = process.exitValue(); System.out.println(value);
//输出信息 InputStreamReader is = new InputStreamReader(process.getInputStream(), Charset.forName("GBK")); BufferedReader br = new BufferedReader(is); String line; while ((line = br.readLine()) != null) { System.out.println(line); } //错误信息 is = new InputStreamReader(process.getErrorStream(), Charset.forName("GBK")); br = new BufferedReader(is); while ((line = br.readLine()) != null) { System.out.println(line); } //关闭连接(最好放在finally中) process.destroy();
ProcessBuilder 执行命令,打开软件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
try { //启动 windows 的计算器程序,第一个参数必须是可执行程序 String[] cmd1 = {"C:/Java/PortableGit/bin/bash.exe", "-c", "git"}; /** 创建ProcessBuilder对象,设置指令列表*/ ProcessBuilder processBuilder = new ProcessBuilder(cmd1); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); InputStream in = process.getInputStream(); byte[] re = new byte[1024]; while (in.read(re) != -1) { System.out.println("==>" + new String(re, Charset.forName("GBK"))); } in.close(); if (process.isAlive()) { process.waitFor(); } } catch (Exception e) { e.printStackTrace(); }
/** 创建ProcessBuilder对象,设置指令列表*/ ProcessBuilder processBuilder = new ProcessBuilder(cmd1); processBuilder.redirectErrorStream(true); Process process = processBuilder.start();
InputStream in = process.getInputStream(); byte[] re = new byte[1024]; while (in.read(re) != -1) { System.out.println("==>" + new String(re, Charset.forName("GBK"))); } in.close(); if (process.isAlive()) { process.waitFor(); } } catch (Exception e) { e.printStackTrace(); } }