1. 程式人生 > >java中呼叫shell命令

java中呼叫shell命令

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Shell {
	public static void main(String[] args) {
		String command = "ls -l";
		
		test(command);
	}
	
	public static void test(String command) {
		Process process = null;
		
		try {
			process = Runtime.getRuntime().exec(command);
			BufferedReader reader = new BufferedReader(
			 			new InputStreamReader(
			 					process.getInputStream()));
			String data = "";
			while((data = reader.readLine()) != null) {
				System.out.println(data);
			}
			
			int exitValue = process.waitFor();
			
			if(exitValue != 0) {
				System.out.println("error");
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	} 
}

Process exec(String command) :在一個單獨的執行緒中執行此命令

waitFor()命令執行成功返回0,getInputStream()獲取命令的輸出


  1. Process exec(String command)
  2. 在單獨的程序中執行指定的字串命令。