2015-02-08 81 views
1

我需要一些关于我的Java桌面应用程序的帮助。我有一个按钮(我的意图)终端(Linux)或提示符/ cmd(Windows)并传递一些命令(我试图使用ping命令)。打开终端/提示并通过一个命令(ping)

我只知道如何打开终端,但我无法传递命令。我如何做到这一点?

谢谢。

编辑:

我此时代码:

 Runtime rt = Runtime.getRuntime(); 
     String sistemaOperacional = System.getProperty("os.name").toLowerCase(); 
      String ip = "192.168.7.1"; 
      String comando = "ping -c 100 "+ip; 

      if (sistemaOperacional.contains("linux")){ 
       try { 
        rt.exec("gnome-terminal "); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
      else if (sistemaOperacional.contains("win")){ 

       try { 
        rt.exec("cmd.exe /c start command"); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

      } 
      else{ 
       JOptionPane.showMessageDialog(null, "Não foi possível identificar o sistema operacional!"); 
      } 
+0

您可以编辑您的问题以包含启动终端或命令提示符的代码吗? – Kenster 2015-02-08 14:47:30

+0

已编辑。这称为终端,但没有命令... – Tux123 2015-02-08 19:16:28

回答

0

您应搜索的文档,你的终端,设置将在终端启动时运行命令的选项。例如,对于xterm-e,使运行在Java代码中xterm命令你会怎么做,例如:

Runtime.getRuntime().exec("xterm -e ls;read"); // read is here just for the terminal not to close right away 

弹出一个终端,运行ls,并等待用户按Enter键,直到终端关闭。

但是由于您不应该依赖于您的用户拥有某个默认终端,因此您最好使用系统默认值,并且-e是许多终端之间的标准参数(例如,gnome-terminal也使用此参数):

Runtime.getRuntime().exec("x-terminal-emulator -e ls;read"); 
+0

在你把“读”的地方是我通过我的var内容? – Tux123 2015-02-08 19:34:07

+0

你可以在'-e'后加任何命令。由于command只是一个字符串,你可以使用你的变量在你的Java代码中编写这个命令,是的。我把'read'放到了终端上,弹出后不会关闭。保持提供'-e'参数的终端可能是一个更好的方法(当然,如果你需要的话),但我没有找到。 – gvlasov 2015-02-08 19:50:55

+0

是的,它的工作原理(在Linux上)。我尝试使用'ping'命令并工作。 '“x-terminal-emulator -e”+ command'。在Windows中,我可以尝试相同的事情吗? – Tux123 2015-02-08 20:12:02

相关问题