首頁  >  文章  >  Java  >  如何在Java中執行外部程序,例如Windows Media Player?

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

WBOY
WBOY轉載
2023-09-04 09:25:021086瀏覽

如何在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 . . . . . . . .

以上是如何在Java中執行外部程序,例如Windows Media Player?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除