java执行shell或者cmd命令

Shell: http://blog.csdn.net/bhq2010/article/details/7414788
Java执行Linux命令并返回命令结果 http://blog.csdn.net/jiafu1115/article/details/6941245
使用Java中的Runtime.exec()执行Windows命令 http://walsh.iteye.com/blog/449051

Java 可以通过 Runtime 调用Linux命令,形式如下:
Runtime.getRuntime().exec(command)
但是这样执行时没有任何输出,因为调用 Runtime.exec 方法将产生一个本地的进程,并返回一个Process子类的实例(注意:Runtime.getRuntime().exec(command)返回的是一个Process类的实例)该实例可用于控制进程或取得进程的相关信息。
由于调用 Runtime.exec 方法所创建的子进程没有自己的终端或控制台,因此该子进程的标准IO(如stdin,stdou,stderr)都通过 Process.getOutputStream(),Process.getInputStream(), Process.getErrorStream() 方法重定向给它的父进程了。
/**
	 * 运行shell脚本
	 * @param shell 需要运行的shell脚本
	 */
	public static void execShell(String shell){
		try {
			Runtime rt = Runtime.getRuntime();
			rt.exec(shell);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


/**
	 * 运行shell
	 * 
	 * @param shStr
	 *            需要执行的shell
	 * @return
	 * @throws IOException
	 */
	public static List runShell(String shStr) throws Exception {
		List<String> strList = new ArrayList();

		Process process;
		process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr},null,null);
		InputStreamReader ir = new InputStreamReader(process
				.getInputStream());
		LineNumberReader input = new LineNumberReader(ir);
		String line;
		process.waitFor();
		while ((line = input.readLine()) != null){
		    strList.add(line);
		}
		
		return strList;
	}



CMD: http://qiaolevip.iteye.com/blog/1693623
package com.anxin.cmd.test;

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

/**
 * @author: (le.qiao)
 * @e-mail: [email protected]
 * @myblog: <a href="http://qiaolevip.iteye.com">http://qiaolevip.iteye.com</a>
 * @date: 2012-10-8
 * 
 */
public class Command {

	public static void main(String[] args) {
		try {
			Runtime rt = Runtime.getRuntime();
			String[] args = new String[]{"cmd","/c",command};
			Process pr = rt.exec(args,null,null);
			//Process pr = rt.exec("cmd /c dir"); // cmd /c calc
			// Process pr = rt.exec("D:\\xunlei\\project.aspx");

			BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream(), "GBK"));

			String line = null;

			while ((line = input.readLine()) != null) {
				System.out.println(line);
			}

			int exitVal = pr.waitFor();
			System.out.println("Exited with error code " + exitVal);

		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
		}
	}
}

猜你喜欢

转载自panyongzheng.iteye.com/blog/1947130