Wednesday, October 17, 2012

How do I run a batch file from my Java Application?

Sometimes we want to run a batch file from our Java Application. This batch could be either a .bat file or a .sh file, it depends on which operating system are we using.

After some research ... I created a class that do the job.

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();
}
}
}
view raw gistfile1.java hosted with ❤ by GitHub
Basically, we have 4 parameters.


  • 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