如何在Java中執行外部程式,例如Windows Media Player?


使用Runtime類

Java提供了一個名為java.lang.Runtime的類,使用這個類可以與當前環境互動。

該類的**`getRuntime()`**(靜態)方法返回與當前應用程式關聯的Runtime物件。

exec()方法接受一個字串值,該值表示在當前環境(系統)中執行程序的命令,並執行它。

因此,要使用Runtime類執行外部應用程式:

  • 使用**`getRuntime()`**方法獲取執行時物件。

  • 透過將外部程式的路徑作為字串值傳遞給**`exec()`**方法來執行所需程序。

示例

import java.io.IOException;
public class Trail {
   public static void main(String args[]) throws IOException {
      Runtime run = Runtime.getRuntime();
      System.out.println("Executing the external program . . . . . . . .");
      String file = "C:\Program Files\Windows Media Player\wmplayer.exe";
      run.exec(file);
   }
}

輸出

System.out.println("Executing the external program . . . . . . . .

使用ProcessBuilder類

類似地,**ProcessBuilder**類的建構函式接受一個可變引數,該引數的型別為字串,表示要執行的程序的命令及其引數,並構造一個物件。

此類的**start()**方法啟動/執行當前ProcessBuilder中的程序。因此,要使用**ProcessBuilder類**執行外部程式:

  • 透過將要執行的程序的命令及其引數作為引數傳遞給其建構函式來例項化ProcessBuilder類。

  • 透過在上面建立的物件上呼叫**start()**方法來執行程序。

示例

 線上演示

import java.io.IOException;
public class ExternalProcess {
   public static void main(String args[]) throws IOException {
      String command = "C:\Program Files\Windows Media Player\wmplayer.exe";
      String arg = "D:\sample.mp3";
      //Building a process
      ProcessBuilder builder = new ProcessBuilder(command, arg);
      System.out.println("Executing the external program . . . . . . . .");
      //Starting the process
      builder.start();
   }
}

輸出

Executing the external program . . . . . . . .

更新於:2019年10月11日

903 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告