Javaから外部のコマンドを実行することあると思います。
Runtime.getRuntime().exec()はWindowsとLinuxで挙動が異なったり、引数にダブルクォーテーションが入ると意図した挙動にならなかったりするため、バッチファイルを作成しそのファイルを呼ぶ形を取ります。
渡す引数は実際に実行したいコマンドをcmdに渡します。
実行するコマンドを書き込むファイルをbatPathに渡します。この時ファイル名は.batになるようにしておきます。
Windowsの場合はそのまま.batファイルを実行させます。
Linuxの場合はsh XXX.bat を実行させます。
/**
* Javaからコマンドを実行する
*
* @param cmd
* 実行するコマンド
* @param batPath
* 実行するコマンドを書き込むファイル
*/
public static void doExec(String cmd, String batPath) {
File f = new File(batPath);
if (f.exists()) {
if (!f.delete()) {
throw new Exception("");
}
}
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(f));
bos.write(cmd.getBytes());
bos.close();
} catch (FileNotFoundException e) {
throw new Exception(e);
} catch (IOException e) {
throw new Exception(e);
}
String execCmd = null;
if (isWindows()) {
execCmd = batPath;
} else {
execCmd = "/bin/sh " + batPath;
}
Process runtimeProcess;
int processCompleted = -1;
try {
runtimeProcess = Runtime.getRuntime().exec(execCmd);
processCompleted = runtimeProcess.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(
runtimeProcess.getErrorStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.printf(line);
}
} catch (IOException e) {
throw new Exception(e);
} catch (InterruptedException e) {
throw new Exception(e);
}
if (processCompleted != 0) {
throw new Exception("");
}
}


