最近在做产品遇到java在windows下面调用bat脚本和在linux下调用shell脚本,现在记录一下以便以后查阅。
首先贴出RuntimeUtils工具类,此类简化了 Runtime中exec的调用
package com.zohan.www.util;
import java.io.File;
import java.io.IOException;
import org.apache.commons.lang3.StringUtils;
/**
* @ClassName: RuntimeUtils
* @Description: runtime工具类 简化了执行命令行
* @author zohan inlw@sina.com
* @date 2012-10-30 下午8:42:09
*
*/
public class RuntimeUtils {
/**
*
* @Title: exec
* @Description: 简化执行命令行
* @param command 命令行
* @param envp 环境变量
* @param dir 路径
* @return Process 返回类型
* @throws IOException
*/
public static Process exec(String command, String envp, String dir)
throws IOException {
String regex = "\\s+";
String args[] = null;
String envps[] = null;
if (!StringUtils.isEmpty(command)) {
args = command.split(regex);
}
if (!StringUtils.isEmpty(envp)) {
envps = envp.split(regex);
}
return Runtime.getRuntime().exec(args, envps, new File(dir));
}
}
下面是开启tomcat和关闭tomcat的测试类TestRuntimeUtils
package com.zohan.ww.system;
import org.junit.Test;
import com.zohan.www.util.RuntimeUtils;
/**
* @ClassName: TestRuntimeUtils
* @Description: RuntimeUtils测试
* @author zohan inlw@sina.com
* @date 2012-10-30 下午9:02:48
*
*/
public class TestRuntimeUtils {
/**
*
* @Title: testStartTomcat
* @Description: windows 下启动tomcat
* @throws Exception
* @return void 返回类型
* @throws
*/
@Test
public void testStartTomcat() throws Exception {
String command = "cmd.exe /c startup.bat";
String dir = "D:\\ehcache\\apache-tomcat-6.0.35\\bin";
Process process = RuntimeUtils.exec(command, null, dir);
int i = process.waitFor();
System.exit(i);
}
/**
*
* @Title: testStopTomcat
* @Description: windows 下关闭tomcat
* @throws Exception
* 设定文件
* @return void 返回类型
* @throws
*/
@Test
public void testStopTomcat() throws Exception {
String command = "cmd.exe /c start shutdown.bat";
String dir = "D:\\ehcache\\apache-tomcat-6.0.35\\bin";
Process process = RuntimeUtils.exec(command, null, dir);
int i = process.waitFor();
System.exit(i);
}
/**
*
* @Title: testStartWas
* @Description: linux 下 启动was服务
* @throws Exception 设定文件
* @return void 返回类型
* @throws
*/
@Test
public void testStartWas() throws Exception{
String command = "sh startServer.sh server1";
String dir = "/usr/IBM/WebSphere/AppServer/profiles/AppSrv01/bin";
Process process = RuntimeUtils.exec(command, null, dir);
int i = process.waitFor();
System.exit(i);
}
/**
*
* @Title: testStopWas
* @Description: linux 下停止was服务
* @throws Exception 设定文件
* @return void 返回类型
* @throws
*/
@Test
public void testStopWas()throws Exception{
String command = "sh stopServer.sh server1 -username admin password";
String dir = "/usr/IBM/WebSphere/AppServer/profiles/AppSrv01/bin";
Process process = RuntimeUtils.exec(command, null, dir);
int i = process.waitFor();
System.exit(i);
}
}
注意事项:在此过程中环境为null,会继承当前线程的环境变量。
本文介绍了如何使用RuntimeUtils工具类简化Java在不同操作系统下执行bat和shell脚本的过程,提供了针对Windows下启动和关闭Tomcat及Linux下启动和停止WebSphere应用服务的示例。
892

被折叠的 条评论
为什么被折叠?



