簡體   English   中英

使用Runtime.exec而不使用cmd.exe運行批處理文件

[英]Run batch file using Runtime.exec without using cmd.exe

我正在運行一個執行腳本的Java應用程序。 相關代碼是

    String command [] = new String [2];
    command[0] =  "customSearch";
    command[1] =  query;    

    Process process = Runtime.getRuntime().exec(command);

該代碼在Linux上運行,因為我在/usr/bin目錄中放置了一個名為customSearch的腳本。 以類似的方式,我在Windows中創建了一個名為customSearch.bat的批處理文件,並確保該文件位於PATH 但是,此Java代碼在Windows上不起作用,因為如線程所述,“單獨的批處理文件不可執行”。

因此,要使其在Windows上運行,我不得不說

    command[0] =  "cmd /c start customSearch";

但是,我不想這樣做,因為這在Linux上不起作用。 如何在Windows上運行批處理文件而不更改command[0]

您可以添加檢查操作系統是否為Windows,然后執行custom-windows-batch-runner-snippet。

例如,我使用netstat命令創建了一個簡單的test.bat文件:

netstat

這是我通過Java代碼片段執行的方式:

String os = System.getProperty("os.name");
if (os.toLowerCase().indexOf("win") >= 0) {
    command = new String[1];
    command[0] = "test.bat";  

    Process process = Runtime.getRuntime().exec(command);
    BufferedReader is = new BufferedReader(
                            new InputStreamReader(process.getInputStream()));
    String line;
    while ((line = is.readLine()) != null) {
       System.out.println(line);
    }
}

這是控制台中的結果:

D:\workspace\SO>netstat

Active Connections

  Proto  Local Address          Foreign Address        State
  TCP    127.0.0.1:19872        hp:49266               ESTABLISHED
  TCP    127.0.0.1:49169        hp:49170               ESTABLISHED
  TCP    127.0.0.1:49170        hp:49169               ESTABLISHED'
....

更好的是,您可以使用if語句包裝每個特定於操作系統的命令執行片段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM