簡體   English   中英

從 Java 打開一個新的提示/終端窗口

[英]Open a new prompt/terminal window from Java

我想打開一個新的終端窗口,它會在打開時運行某個命令。 它最好需要是一個真正的本機窗口,而且我不介意為 linux/osx/windows 編寫不同的代碼。

我假設模擬終端可以工作,只要它支持真正終端可以做的一切,而不僅僅是打印命令的輸出行。

這會起作用嗎?

// windows only
Process p = Runtime.getRuntime().exec("cmd /c start cmd.exe");
p.waitFor();

打開一個實際的終端窗口肯定需要為每個操作系統提供不同的代碼。 對於 Mac,您需要類似的東西:

Runtime.getRuntime().exec("/usr/bin/open -a Terminal /path/to/the/executable");

在 Ubuntu(X11 桌面)10.04 ~ 14.04 和其他 Debian 發行版上使用過它。 工作正常; 不過,您可以考慮使用 Java 的ProcessBuilder

// GNU/Linux -- example

Runtime.getRuntime().exec("/usr/bin/x-terminal-emulator --disable-factory -e cat README.txt");

 //  --disable-factory    Do not register with the activation nameserver, do not re-use an active terminal
//    -e                  Execute the argument to this option inside the terminal.

您需要有關正在運行的操作系統的信息。 為此,您可以使用這樣的代碼:

public static void main(String[] args)
    {
        String nameOS = "os.name";        
        String versionOS = "os.version";        
        String architectureOS = "os.arch";
        System.out.println("\n    The information about OS");
        System.out.println("\nName of the OS: " + 
        System.getProperty(nameOS));
        System.out.println("Version of the OS: " + 
        System.getProperty(versionOS));
        System.out.println("Architecture of THe OS: " + 
        System.getProperty(architectureOS));
    }

然后對於每個操作系統,您將不得不使用 Bala R 和 Mike Baranczak 所描述的不同調用

為了讓 Java 使用 Windows taskkill,試試這個:

    try {
      // start notepad before running this app
      Process p1 = Runtime.getRuntime().exec("cmd /c start cmd.exe"); // launch terminal first
      p1.waitFor();
      Process p2 = Runtime.getRuntime().exec( "taskkill /F /IM notepad.exe" );  // now send taskkill command
      p2.waitFor();
      Process p3 = Runtime.getRuntime().exec( "taskkill /F /IM cmd.exe" );  // finally, close terminal
      p3.waitFor();
    } catch (IOException ex) {
        System.out.println(ex);
    } catch (InterruptedException ex) {
        Logger.getLogger(RT2_JFrame.class.getName()).log(Level.SEVERE, null, ex);
    } // close try-catch-catch

您需要在 taskkill 工作之前運行 cmd 終端。

暫無
暫無

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

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