Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chạy chương trình ngoài (như Windows Media Player) từ Java

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ểmRuntime.exec()ProcessBuilder
APICũ (Java 1.0)Mới (Java 1.5+)
Truyền tham sốChuỗi đơn hoặc mảngList/String varargs
Môi trường (env)Khó tùy chỉnhDễ dàng qua environment()
Redirect I/OPhứ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