Java调用Linux命令(cd的处理)
一、Java调用Linux系统的命令非常简单
这是一个非常常用的调用方法示例:
1 public String executeLinuxCmd(String cmd) { 2 System.out.println("got cmd job : " + cmd); 3 Runtime run = Runtime.getRuntime(); 4 try { 5 Process process = run.exec(cmd); 6 InputStream in = process.getInputStream(); 7 BufferedReader bs = new BufferedReader(new InputStreamReader(in)); 8 // System.out.println("[check] now size \n"+bs.readLine());
StringBuffer out = new StringBuffer();
byte[] b = new byte[8192];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
System.out.println("job result [" + out.toString() + "]");
14 in.close(); 15 // process.waitFor(); 16 process.destroy(); 17 return result; 18 } catch (IOException e) { 19 e.printStackTrace(); 20 } 21 return null; 22 }
二、含有管道符(|)多级命令串联查询
public List<String> executeLinuxCmd(String cmd) { System.out.println("got cmd job : " + cmd); Runtime run = Runtime.getRuntime(); try { // Process process = run.exec(cmd); Process process = run.exec(new String[] {"/bin/sh", "-c", cmd}); InputStream in = process.getInputStream(); BufferedReader bs = new BufferedReader(new InputStreamReader(in)); List<String> list = new ArrayList<String>(); String result = null; while ((result = bs.readLine()) != null) { System.out.println("job result [" + result + "]"); list.add(result); } in.close(); // process.waitFor(); process.destroy(); return list; } catch (IOException e) { e.printStackTrace(); } return null; }
上一个教程:十三个有彩蛋的Linux命令