Java执行shell工具类

原创
2017/01/23 09:47
阅读数 2.8K

执行shell工具类

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ShellUtils {

	private static final Logger logger = LoggerFactory.getLogger(ShellUtils.class);

	public void executeCommand(final String command) throws IOException {
		final File root = new File(".");
		final Process p = Runtime.getRuntime().exec(command, null, root);
		//管道sh -c ps -ef | grep -v grep
		//new ProcessBuilder("sh", "-c", "ps -ef | grep -v grep");
//		ProcessBuilder bulider = new ProcessBuilder(command);
//		Process p = bulider.start();
		Reader input = new InputStreamReader(p.getInputStream());
		Reader errors = new InputStreamReader(p.getErrorStream());

		for (String line : IOUtils.readLines(input)) {
			if (line.startsWith("[ERROR]")) {
				logger.error(line);
			} else if (line.startsWith("[WARNING]")) {
				logger.warn(line);
			} else {
				logger.info(line);
			}
		}

		for (String line : IOUtils.readLines(errors)) {
			if (line.startsWith("[ERROR]")) {
				logger.error(line);
			} else if (line.startsWith("[WARNING]")) {
				logger.warn(line);
			} else {
				logger.info(line);
			}
		}

		p.getOutputStream().close();

		try {
			if (p.waitFor() != 0) {
				logger.warn("The command '" + command + "' did not complete successfully");
			}
		} catch (final InterruptedException e) {
			throw new IllegalStateException(e);
		}
	}
}

 

展开阅读全文
打赏
0
1 收藏
分享
加载中
更多评论
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部