Java的java.lang.Runtime类提供了运行 Windows下cmd环境的方法exec(String command),所有在Windows cmd命令窗口下执行的程序,都能利用这个方法执行。
下边提供两个封装后的代码,一个是查看程序是否在运行,另一个是启动程序:
1、查看程序是否在运行:其中tasklist /FI "IMAGENAME eq processName.exe"是在Windows CMD命令下执行的命令
/** * 判断某个进程是否在运行中 * @param processName * @return */ public static boolean isRunning(String processName) { BufferedReader bufferedReader = null; try { Process proc = Runtime.getRuntime().exec("tasklist /FI \"IMAGENAME eq " + processName + "\""); bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = null; while ((line = bufferedReader.readLine()) != null) { if (line.contains(processName)) //判断是否存在 { return true; } } return false; } catch (Exception ex) { ex.printStackTrace(); return false; } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (Exception ex) { } } } }
2、执行某个程序,comand例为:start "" "E:\\CardListen\\CardReaderServer.exe" "127.0.0.1" "8080",详情可看CMD start命令
/** * 执行Cmd命令 * @param command * @return * @throws IOException */ public static String executeCmd(String command) throws IOException { 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) { build.append(line); } return build.toString(); }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-20 18:57:05