Berikut adalah contoh cara menjalankan skrip Unix bash atau Windows bat / cmd dari Java. Argumen dapat disampaikan pada skrip dan output yang diterima dari skrip. Metode ini menerima sejumlah argumen yang berubah-ubah.
public static void runScript(String path, String... args) {
try {
String[] cmd = new String[args.length + 1];
cmd[0] = path;
int count = 0;
for (String s : args) {
cmd[++count] = args[count - 1];
}
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
try {
process.waitFor();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
while (bufferedReader.ready()) {
System.out.println("Received from script: " + bufferedReader.readLine());
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
System.exit(1);
}
}
Saat berjalan di Unix / Linux, lintasan harus seperti Unix (dengan '/' sebagai pemisah), saat dijalankan di Windows - gunakan '\'. Hier adalah contoh skrip bash (test.sh) yang menerima jumlah argumen sembarang dan menggandakan setiap argumen:
#!/bin/bash
counter=0
while [ $# -gt 0 ]
do
echo argument $((counter +=1)): $1
echo doubling argument $((counter)): $(($1+$1))
shift
done
Saat menelepon
runScript("path_to_script/test.sh", "1", "2")
pada Unix / Linux, hasilnya adalah:
Received from script: argument 1: 1
Received from script: doubling argument 1: 2
Received from script: argument 2: 2
Received from script: doubling argument 2: 4
Hier adalah cmd Windows script test.cmd sederhana yang menghitung jumlah argumen input:
@echo off
set a=0
for %%x in (%*) do Set /A a+=1
echo %a% arguments received
Saat memanggil skrip di Windows
runScript("path_to_script\\test.cmd", "1", "2", "3")
Outputnya adalah
Received from script: 3 arguments received