public class Test { public static void main(String[] args) throws Exception { try { //execute shell command: df -k . Process fileSystemDfInfo = Runtime.getRuntime().exec("df -k ."); BufferedReader reader = new BufferedReader( new InputStreamReader(fileSystemDfInfo.getInputStream())); String contentLine; while ((contentLine = reader.readLine()) != null){ //do something with contentLine System.out.println(contentLine); } reader.close(); } catch(Exception e) { e.printStackTrace(); } } }
===
import java.io.File; import java.io.BufferedReader; import java.io.InputStreamReader; public class RunSystemCommand { public static void main(String args[]) { String s = null; // system command to run String cmd = "ls > fred.txt"; // set the working directory for the OS command processor File workDir = new File("/dir1/dir2"); try { Process p = Runtime.getRuntime().exec(cmd, null, workDir); int i = p.waitFor(); if (i == 0) { BufferedReader stdInput = new BufferedReader( new InputStreamReader(p.getInputStream())); // read the output from the command while ((s = stdInput.readLine()) != null) { System.out.println(s); } } else { BufferedReader stdErr = new BufferedReader( new InputStreamReader(p.getErrorStream())); // read the output from the command while ((s = stdErr.readLine()) != null) { System.out.println(s); } } } catch (Exception e) { System.out.println(e); } } }
Resource: 1. http://bjyzxxds.iteye.com/blog/460126
相关资源:java代码中调用linux/unix命令