After some research ... I created a class that do the job.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ng.framework.util; | |
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import org.apache.commons.logging.Log; | |
import org.apache.commons.logging.LogFactory; | |
public class NGOSUtil { | |
private static final Log LOG = LogFactory.getLog(NGOSUtil.class); | |
public static final String EXEC_WINDOWS = " cmd /c start "; | |
public static final String EXEC_UNIX = " /bin/bash "; | |
public static boolean isWindows() { | |
String os = System.getProperty("os.name").toLowerCase(); | |
// windows | |
return (os.indexOf("win") >= 0); | |
} | |
public static boolean isMac() { | |
String os = System.getProperty("os.name").toLowerCase(); | |
// Mac | |
return (os.indexOf("mac") >= 0); | |
} | |
public static boolean isUnix() { | |
String os = System.getProperty("os.name").toLowerCase(); | |
// linux or unix | |
return (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0); | |
} | |
public static boolean isSolaris() { | |
String os = System.getProperty("os.name").toLowerCase(); | |
// Solaris | |
return (os.indexOf("sunos") >= 0); | |
} | |
public static void exec(String programAbsolutePath, String parameters, String[] environmentVariables, File baseDirectory) { | |
String exec = isUnix() ? EXEC_UNIX : EXEC_WINDOWS; | |
String str = null; | |
try { | |
Process p = Runtime.getRuntime().exec(exec + programAbsolutePath + " " + parameters, environmentVariables, | |
baseDirectory); | |
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); | |
LOG.debug("Here is the standard output of the command: " + programAbsolutePath); | |
while ((str = stdInput.readLine()) != null) { | |
LOG.debug(str); | |
} | |
} catch (IOException e) { | |
LOG.error("exception happened - here's what I know: ", e); | |
e.printStackTrace(); | |
} | |
} | |
} |
- programAbsolutePath: Where is the batch file to execute?
- parameters: Which are the parameters of the batch file?
- environmentVariables: If you want to override some environment variables
- baseDirectory: Which will be the base directory of the batch?. This could be usefull when the batch file use relative paths in its process.
This class only executes batches for unix/windows. If you want to use it in other Operating Systems you should specify which are the execution path (like EXEC_WINDOWS and EXEC_UNIX constants)
That's all.
No comments:
Post a Comment