Java調(diào)用Linux命令(cd的處理)
一、Java調(diào)用Linux系統(tǒng)的命令非常簡(jiǎn)單
這是一個(gè)非常常用的調(diào)用方法示例:
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 }
二、含有管道符(|)多級(jí)命令串聯(lián)查詢
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; }
上一個(gè)教程:十三個(gè)有彩蛋的Linux命令
下一個(gè)教程:Linux命令中Ctrl+z、Ctrl+c和Ctrl+d