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. 在单独的进程中执行指定的字符串命令。

你可能感兴趣的:(java)