Java判断应用程序启动状态并打开或关闭应用程序
程序员文章站
2024-01-17 14:44:10
...
package com.anxin.ssk.util; import java.awt.Desktop; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.anxin.ssk.common.Config; public class CommandUtil { private static Logger log = LoggerFactory.getLogger(CommandUtil.class); /** * 执行cmd命令 * * @param command * @throws IOException */ public static String executeCmd(String command) throws IOException { log.info("Execute command : " + command); Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("cmd /c " + command); BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line = null; StringBuilder build = new StringBuilder(); while ((line = br.readLine()) != null) { log.info(line); build.append(line); } return build.toString(); } /** * 检测应用程序运行状态 * * @param programName * @return * @throws IOException */ public static boolean checkProgramStatus(String programName) throws IOException { log.info("检测应用程序:" + programName + "运行状态"); boolean result = false; // Config.Local.DATA_EXE_ADSUP String cmdLines = executeCmd("tasklist |findstr /i \"" + programName + "\""); if (StringUtils.isNotEmpty(cmdLines)) { log.info("后台任务列表找到" + programName + "程序正在运行······重启应用程序"); result = true; } else { log.error("没有在后台任务列表找到" + programName + "程序······重新打开新的应用程序"); } return result; } /** * 启动应用程序 * * @param programName * @return * @throws IOException */ public static void startProgram(String programPath) throws IOException { log.info("启动应用程序:" + programPath); if (StringUtils.isNotBlank(programPath)) { Desktop.getDesktop().open(new File(programPath)); // String programName = programPath.substring(programPath.lastIndexOf("\\") + 1, // programPath.lastIndexOf(".")); // executeCmd("start \"" + programName + "\" \"" + programPath + "\""); } } /** * 关闭应用程序 * * @param programName * @return * @throws IOException */ public static void closeProgram(String programName) throws IOException { log.info("关闭应用程序:" + programName); if (StringUtils.isNotBlank(programName)) { executeCmd("taskkill /F /IM " + programName); } } /** * 重启应用程序,若启动则重启,否则打开 * * @param programName * @return * @throws IOException */ public static void restartProgram(String programName, String programPath) throws IOException { log.info("重启应用程序:" + programName); if (checkProgramStatus(programName)) { closeProgram(programName); startProgram(programPath); } else { startProgram(programPath); } } public static void main(String[] args) { try { String programPath = "C:\\Program Files\\2345Pic\\2345PicViewer.exe"; // startProgram(programName); String programName = "2345PicViewer.exe"; restartProgram(programName, programPath); } catch (IOException e) { e.printStackTrace(); } } }