`

java 执行cmd命令

 
阅读更多
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;



public class ExecCommand {

	public static String execCommand(String command){
		Runtime runtime = Runtime.getRuntime();
		String errorMSG = "";
		
		try {
			String[] args = new String[]{"cmd","/c",command};
			//String[] args = new String[]{"sh","-?/c",command};
			
			Process pro = runtime.exec(args);
			//Process pro = runtime.exec("c://///////.exe");
			
			InputStream in = pro.getErrorStream();
			InputStreamReader isr = new InputStreamReader(in);

			BufferedReader br = new BufferedReader(isr);

			String line = null;
			
			while ( (line = br.readLine()) != null){
				errorMSG += line+"\n";
				System.out.println(errorMSG);
			}
			
			//检查命令是否失败
			try {
				if(pro.waitFor()!=0){
					System.err.println("exit value:" + pro.exitValue());
				}
			} catch (InterruptedException e) {
				System.err.println();
				e.printStackTrace();
				
			}

		} catch (IOException e) {
			System.out.println("error Message:"+e.getMessage());
			e.printStackTrace();
		} finally{
			return errorMSG;
		}
		
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(execCommand("java -version"));
	}

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics