java程序调用CMD命令启动tomcat替换环境变量
出现问题:
此时不应有 files\java\jdk1.8.0_92\bin\java.exe""(本地未出现问题,服务器环境出现)
出现原因:
1:环境变量java_home配置路径中的空格问题
2:系统环境变量路径首尾出现双引号 " 为多余
解决方法:
1:原路径c:\program files\java\jdk1.8.0_92,需替换为c:\progra~1\java\jdk1.8.0_92 ;
2:将相关环境变量路径的首尾双引号 “ 去掉 ;
如:
import java.util.concurrent.executorservice; import java.util.concurrent.executors; import java.util.concurrent.future;
public static map<string, string> execute(string directory,string[] cmd){ map<string, string> result = new hashmap<>(); process p = null; try { processbuilder builder = new processbuilder(cmd); file file = new file(directory) ; builder.directory(file); map<string, string> env = builder.environment(); env.put("catalina_home", file.getparent()); env.put("catalina_base", file.getparent()); logger.info("=: -----------------------"); for(string str : env.keyset()){ if(env.get(str) != null){ env.put(str, env.get(str).replaceall("program files", "progra~1")); } logger.info(str+"=: "+env.get(str)); } logger.info("=: -----------------------"); string javahome = system.getenv("java_home"); if(stringutils.isnotempty(javahome)) { javahome = javahome.replace("%20", " ").replaceall("program files", "progra~1"); } env.put("java_home", javahome); //环境可能是path 或 path string _path = env.get("path"); if(stringutils.isnotempty(_path)){ env.put("path", _path.replaceall("\"", "")); } string _path = env.get("path"); if(stringutils.isnotempty(_path)){ env.put("path", _path.replaceall("\"", "")); } string _execjava = env.get("_execjava"); if(stringutils.isnotempty(_execjava)){ env.put("_execjava", _execjava.replaceall("\"", "")); } string _runjava = env.get("_runjava"); if(stringutils.isnotempty(_runjava)){ env.put("_runjava", _runjava.replaceall("\"", "")); } string _runjdb = env.get("_runjdb"); if(stringutils.isnotempty(_runjdb)){ env.put("_runjdb", _runjdb.replaceall("\"", "")); } for(string str : env.keyset()){ logger.info(str+"=: "+env.get(str)); } logger.info("正在执行命令...." + builder.directory()); p = builder.start(); logger.info("正在执行命令...."); inputstream errorstream = p.geterrorstream(); executorservice exec = executors.newcachedthreadpool(); future<string> errorsubmit = exec.submit(new workcallable(p, errorstream,"error")); inputstream correctstream = p.getinputstream(); future<string> correctsubmit = exec.submit(new workcallable(p, correctstream,"stdout")); logger.info("正在执行命令2...."); string errormsg = errorsubmit.get(); string successmsg = correctsubmit.get(); logger.info(errormsg); logger.info(successmsg); if(stringutils.isempty(errormsg)) { result.put("status", "success"); result.put("msg", successmsg); } else { result.put("status", "error"); result.put("msg", errormsg); } p.waitfor(); exec.shutdown(); } catch (exception e) { result.put("status", "error"); result.put("msg", e.getmessage()); logger.error("执行命令异常,请检查参数",e.getmessage()); } return result; } |