Javaでshellコマンドを実行するサンプルプログラム

Javaコード:

bDelOldFolder = ShellCmdUtils.callShell(“rm -rf /usr/ne/code/");
StringBuilder sb = new StringBuilder(“cd /usr/ne/code/");
sb.append(task.getNeName())
.append(“;")
.append(“chmod -R 755 *;")
.append(“dos2unix build_rpm.sh;")
.append(“./build_rpm.sh;");
String[] command = { “/bin/sh", “-c", sb.toString() };
boolean bBuild = ShellCmdUtils.callShell(command);
// shellを呼び出す
public static boolean callShell(String shellString) {
try {
Process process = Runtime.getRuntime().exec(shellString);
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = new String();
while ((line = br.readLine()) != null) {
LOG.info(line);
}
int exitValue = process.waitFor();
if (0 != exitValue) {
LOG.error(“シェルを呼ぶ失敗, エラーコード :" + exitValue);
return false;
}
br.close();
return true;
} catch (Exception e) {
LOG.error(“シェルを呼ぶ失敗. " + e);
return false;
}
}

public static boolean callShell(String[] shellStrings) {
try {
String[] cmd = { “/bin/sh", “-c", shellString };
Process process = Runtime.getRuntime().exec(shellStrings);
BufferedReader br = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line = new String();
while ((line = br.readLine()) != null) {
LOG.info(line);
}
int exitValue = process.waitFor();
if (0 != exitValue) {
LOG.error(“シェルを呼ぶ失敗, エラーコード:" + exitValue);
return false;
}
br.close();
return true;
} catch (Exception e) {
LOG.error(“シェルを呼ぶ失敗. " + e);
return false;
}
}

Java

Posted by arkgame