日期:2014-05-16  浏览次数:20684 次

java执行linux命令
package com.rockton.gpsrouter.utils;

import java.io.IOException;
import java.io.InputStream;

public final class LinuxCmdEngin {

	public static final String processUseBasic(String command) {
		Process p = null;
		StringBuilder sb = new StringBuilder();
		try {
			String[] comands = new String[] { "/bin/sh", "-c", command };

			p = Runtime.getRuntime().exec(comands);

			String error = read(p.getErrorStream());
			String outInfo = read(p.getInputStream());

			String resultCode = "0";//脚本中输出0表示命令执行成功

			if (error.length() != 0) { //如果错误流中有内容,表明脚本执行有问题
				resultCode = "1";
			}

			sb.append(resultCode);
			sb.append(error);
			sb.append(outInfo);

			p.waitFor();
		} catch (Exception e) {
		} finally {
			try {
				p.getErrorStream().close();
			} catch (Exception e) {
			}
			try {
				p.getInputStream().close();
			} catch (Exception e) {
			}
			try {
				p.getOutputStream().close();
			} catch (Exception e) {
			}
		}
		return sb.toString();
	}

	public static final String read(InputStream in) throws IOException {
		StringBuilder sb = new StringBuilder();

		int ch;

		while (-1 != (ch = in.read()))
			sb.append((char) ch);

		return sb.toString();
	}
}

?? 在JVM中能够顺利的执行linux命令,可以带来很多可以想象的内容,例如,部署在linux上的服务,可以通过web实现在线管理。在我这里,tomcat和一个java桌面应用部署在同一个Linux服务器上, 这个桌面应用程序的网络管理就是通过上面代码实现,实现了在线网络管理。

?

可以进一步拓展,例如让其在线升级,文件上传后,复制了jar后可以立即重启,等等。

?

?

欢迎拍砖!