1

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. 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.

Any ideas as to how to do it ?

Joris Fonck
  • 55
  • 1
  • 5

2 Answers2

4

To understand this, you first need to understand how you would run that command at a shell prompt.

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

Note where the double quotes are. The first argument is -c. The second argument is the stuff inside the quotes; i.e. java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu

Now we translate that into 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. For that you need to use a "terminal" application.

For example, if you are using 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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thanks for your answer. But i still have a problem. I see the gnome-terminal opening, but it close directly after. I'm tried to insert a waitFor() method after calling the process, but didn't work. – Joris Fonck Dec 17 '16 at 11:41
  • Try adding "; sleep 60" at the end of "java ..." command string. Alternatively, see if one of the (many) alternative terminal emulators has an option to not exit immediately. – Stephen C Dec 17 '16 at 11:51
  • The problem is that when I open a terminal, it opens in the /home/user directory. I will insert the absolute path after the java -jar command and the program will work fine. Thank you for you help ! :) – Joris Fonck Dec 17 '16 at 12:03
0

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. There is a good answer on a previous question on how to run shell scripts within Java here.

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.

Community
  • 1
  • 1
Kieran Jennings
  • 321
  • 2
  • 12