简体   繁体   English

在Java程序中执行bash命令

[英]Execute bash command within java program

It's been quite a while since I'm looking for but I don't find the solution. 自寻找以来已经有一段时间了,但找不到解决方案。 I'm trying to execute bash command on Linux within .jar file. 我试图在.jar文件中的Linux上执行bash命令。 For that, I tried many things, including this : 为此,我尝试了很多事情,包括:

Process p = new ProcessBuilder("java", "-jar", "M1_MIAGE_PDL_VIZ_GROUPE3.jar", "menu").start();
Runtime.getRuntime().exec("/bin/sh -c java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu");
Runtime.getRuntime().exec(new String[]{"/bin/sh -c", "java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu"});

So, when I click on the .jar file, I would like to that the program open a bash, and execute the command (java -jar ...), to execute another part of the program. 因此,当我单击.jar文件时,我希望程序打开bash并执行命令(java -jar ...),以执行程序的另一部分。

Any ideas as to how to do it ? 关于如何做的任何想法?

To understand this, you first need to understand how you would run that command at a shell prompt. 要了解这一点,您首先需要了解如何在shell提示符下运行该命令。

$ sh -c "java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu"

Note where the double quotes are. 请注意双引号在哪里。 The first argument is -c . 第一个参数是-c The second argument is the stuff inside the quotes; 第二个参数是引号内的内容。 ie java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu

Now we translate that into Java: 现在我们将其转换为Java:

Process p = new ProcessBuilder(
   "/bin/sh", 
   "-c", 
   "java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu").start();

Having said that, the above doesn't actually achieve anything. 话虽如此,以上实际上并没有取得任何成就。 Certainly, it doesn't open a fresh console window to display the console output etcetera. 当然,它不会打开新的控制台窗口来显示控制台输出等。 Unlike Windows "CMD.exe", UNIX / Linux shells do not provide console / terminal functionality. 与Windows“ CMD.exe”不同,UNIX / Linux外壳不提供控制台/终端功能。 For that you need to use a "terminal" application. 为此,您需要使用“终端”应用程序。

For example, if you are using GNOME 例如,如果您使用的是GNOME

Process p = new ProcessBuilder(
   "gnome-terminal", 
   "-e", 
   "java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu").start();

will (probably) do what you are trying to do. 将(可能)做您想做的事情。

I think the easiest way to do this would be to create a shell script (.sh extension) and then you can easily run that from within the Java program. 我认为最简单的方法是创建一个shell脚本(扩展名为.sh),然后您就可以在Java程序中轻松地运行它。 There is a good answer on a previous question on how to run shell scripts within Java here . 有关于如何在Java中运行shell脚本前一个问题一个很好的答案在这里

To create a shell script you can use any text editor and create a file with the extension .sh and just enter the lines as you would in the bash terminal. 要创建shell脚本,可以使用任何文本编辑器并创建扩展名为.sh的文件,然后像在bash终端中一样输入行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM