ในที่นี้ผมใช้ คำสั่งของจาวาเรียกใช้ไฟล์ test.bat ซึ่งด้านในบรรจุคำสั่งของ dos อยู่คือ "dir" (ไม่รวมเครื่องหมายคำพูด)
หลักการทำงานของมันให้อ่านที่ Comment เลยนะครับ
[src]
import java.io.*;
class Exec {
public static void main(String Argv[]) {
try {
String ls_str; // สร้างตัวแปรไว้กับค่าตัวอักษรที่ได้จากการรัน
Process ls_proc = Runtime.getRuntime().exec("test.bat"); // สร้าง process เพื่อเอาไว้สั่งงาน test.bat อีกต่อหนึ่ง
// get its output (your input) stream
DataInputStream ls_in = new DataInputStream(
ls_proc.getInputStream()); // สร้าง Obj DataInputStream เพื่อเก็บค่าที่ได้จากการรันของ test.bat
try {
// loop เพื่อทำการแสดงผลตัวอักษรลัพธ์ที่ได้
while ((ls_str = ls_in.readLine()) != null) {
System.out.println(ls_str);
}
} catch (IOException e) {
System.exit(0);
}
} catch (IOException e1) {
System.err.println(e1);
System.exit(1);
}
System.exit(0);
}
}
[/src]