java, scalaでOSコマンド実行

Runtime rt = Runtime.getRuntime();
Process p = rt.exec("cp -p foo.txt foo.txt.BACKUP");
p.waitFor();

など。|や>を使いたいときは、

String cmd = "diff foo.txt foo.txt.BACKUP > foo.txt.diff";
String[] cmdArray = {"/bin/sh", "-c", cmd};
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(cmdArray);

というぐあいにArrayにする。

ちなみにscalaだとこんな感じ。

val cmdBody = "diff foo.txt foo.txt.BACKUP > foo.txt.diff"
val cmd = Array("su", "-", "nobody", "-c", cmdBody)
val p = Process(cmd).run
if (p.exitValue != 0) {
p.toString()
println("異常終了 " + p.toString())
}