Java cho phép thực thi tiến trình hệ điều hành qua Runtime.exec() hoặc ProcessBuilder (khuyên dùng).
Cách 1: Runtime.getRuntime().exec()
import java.io.IOException;
public class RuntimeExecDemo {
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
// Đường dẫn chương trình (Windows)
String player = "C:\\Program Files\\Windows Media Player\\wmplayer.exe";
// Có thể kèm tham số file media
String mediaFile = "D:\\music\\song.mp3";
Process process = rt.exec(new String[]{player, mediaFile});
System.out.println("Đã khởi chạy: " + process.pid());
}
}
Cách 2: ProcessBuilder (hiện đại, linh hoạt hơn)
import java.io.IOException;
public class ProcessBuilderDemo {
public static void main(String[] args) throws IOException {
String player = "C:\\Program Files\\Windows Media Player\\wmplayer.exe";
String mediaFile = "D:\\music\\song.mp3";
ProcessBuilder pb = new ProcessBuilder(player, mediaFile);
// Tùy chọn: redirect output/error
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
Process process = pb.start();
System.out.println("Process ID: " + process.pid());
// Đợi kết thúc (tùy chọn)
// int exitCode = process.waitFor();
}
}
So sánh
| Đặc điểm | Runtime.exec() | ProcessBuilder |
|---|---|---|
| API | Cũ (Java 1.0) | Mới (Java 1.5+) |
| Truyền tham số | Chuỗi đơn hoặc mảng | List/String varargs |
| Môi trường (env) | Khó tùy chỉnh | Dễ dàng qua environment() |
| Redirect I/O | Phức tạp | Đơn giản: redirectOutput() |
| Khuyến nghị | ❌ | ✅ |
⚠️ Lưu ý
- Đường dẫn có khoảng trắng → dùng mảng/String[] hoặc ProcessBuilder varargs
- Chương trình GUI (như WMP) chạy nền, Java không đợi nó thoát
- Cross-platform: dùng
Desktop.getDesktop().open(file)để mở file với app mặc định