Execute bash command within java program - java

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 ?

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.

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.

Related

Execute cmd commands from inside a java program

I am trying to execute cmd commands inside a java program using the following code
String command = "clingo F:\\clingo\\food1.lp F:\\clingo\\fooddata.txt"
+ " 0"+" >>F:\\clingo\\foodout.txt";
Process p1 = Runtime.getRuntime().exec(command);
This is executing in java without any exceptions, but the actual command is not running. If the command is run it should create text file foodout.txt in the location mentioned. Nothing is happening.
The actual command is
clingo food1.lp fooddata.txt 0 >>foodout.txt
clingo is a windows executable program. This command works fine when run in command prompt. I want to run this inside java program from click of a button. I have set environment variable for clingo. Clingo and this java project are in the same directory.
Before this i tried below code
String[] command = {"clingo", "food1.lp","fooddata.txt", "0", ">>foodout.txt"};
ProcessBuilder builder = new ProcessBuilder(command);
builder.directory(new File(WorkingDirectoryArea.getText()));
Process process = builder.start();
where Workingdirectoryarea contains the directory location for commands to be run. This code does nothing.
Can someone guide me or provide code sample on how to run the cmd command inside this java program. I am using Netbeans IDE. Thanks.
you said your command works with a command prompt. OK. If you look closely, the command window has a path entry (cmd= echo %PATH%). That's the difference between executing a command in a command window and executing a java process. You have 2 options.
1. Add the path to the process.
2. Add the path to the clingo command (i.e. "f:\path\clingo.exe ...)
Item 1 is especially needed when using dos commands. To add a path environment:
Runtime.getRuntime().exec not finding file in java environment
You are redirecting standard output to a file. This is not part of the command nor a command line parameter. Is the command interpreter that handles this.
You must invoke the command interpreter to run your program like this:
String command = "cmd /c clingo F:\\clingo\\food1.lp F:\\clingo\\fooddata.txt"
+ " 0"+" >>F:\\clingo\\foodout.txt";
Process p1 = Runtime.getRuntime().exec(command);
Note the cmd /cpart which invokes the command interpreter to run your command like you would do on a Windows terminal.
On Linux it would be sh -c or whatever shell you like.
EDIT 1
When running the command, clingo.exe must be in your path or it must be in the default directory for the Java interpreter. If not, you should give the full path to the executable, like this:
String command = "cmd /c F:\\clingo\\clingo F:\\clingo\\food1.lp F:\\clingo\\fooddata.txt"
+ " 0"+" >>F:\\clingo\\foodout.txt";
Try to run
F:\\clingo\\clingo F:\\clingo\\food1.lp F:\\clingo\\fooddata.txt 0 >> F:\\clingo\\foodout.txt
at a Windows prompt and see if it works as expected. If it works it also should work when run from a Java program. Please, replace the clingo path with the right one for your environment.
Your command must be like this: java -jar yourExecuteable.jar yourParameter
In your case: java -jar clingo.jar food1.lp fooddata.txt 0 >>foodout.txt

Start a java application with terminal

I'm trying to create a java application which starts a new terminal without using java -jar. I tried using several methods, but none of them have worked.
I need this to work on osx, I was able to make it on windwos
You have to call your shell as a program
Runtime runtime = Runtime.getRuntime();
String[] args = { "/bin/sh", "-c", " java -jar myjar.jar" };
final Process process = runtime.exec(args);
To respond to your specific request, this is my answer
1/ Create a shell script
For example call it loadJava.sh:
#!/bin/sh
java -jar path/to/jar/file.jar
2/ Call the shell script with this java code that open a terminal and run the shell script
Correct code for OSX is
Runtime.getRuntime().exec("/usr/bin/open -a Terminal /path/to/the/script");

Writing a bash script to run a java program

I'm rank new to bash thus the question.
I've a java program that I've exported as a .jar.
This file when run as
java -jar somefile.jar
goes into an infinite loop and awaits a file name. Based on the correct file path it generates an output.
How do I write a bash script to do automated testing of this project.
I need the scrip to do the following -
Run the program, which is run the same command
provide an array of 5 files as an input to the program
For each file write the output to an log file.
This should do it.
#!/bin/bash
files="$#"
for i in $files;
do
echo "Doing $i"
java -jar somefile.jar <<< "$i"
done
Make sure you chmod u+x filename it first. Then call it like this:
./filename firstfile secondfile thirdfile etc.
Other:
As sjsam pointed out, the use of <<< is a strictly bash thing. You are apparently using bash ("I'm rank new to bash..."), but if you weren't, this would not work.
Suppose my java program is HelloWorld.java. We can run it in 2 ways:
1st using executable jar
2nd by running java class from terminal
create a new text file and name it hello.sh
In hello.sh
!/bin/bash
clear
java -jar HelloWorld.jar
Save it and open terminal:
1 navigate to directory where your HelloWorld.jar is present
2 give permission to terminal to run the bash script by using the following command
sudo chmod 754 hello.sh
3 run you script by running the following command
./hello.sh

How to execute shell script and save in text file command through java in linux

I m using Linux.
I want to call a small executable application from my java command line which is called "wmic". It needs an input query. Output are stored in text file in the specific directory.
When I use the command in Linux Terminal
echo "Hello World" >> /home/kannan/hello.txt
the output is stored in hello.txt file.
but when i call this command from java
Process p = Runtime.getRuntime().exec("echo \"Hello World\" >> /home/kannan/hello1.txt");
the output is not created any hello1.txt file
Please any one help me.
Thanks in Advance.
Use a ProcessBuilder. It makes it easy to redirect output of a command to file as shown below:
new ProcessBuilder("echo", "hello").redirectOutput(new File("output.txt")).start();
If you want to append to the output file:
new ProcessBuilder("echo", "hello").redirectOutput(Redirect.appendTo(new File("output.txt"))).start();
What you are executing is bash command (echo). Your java program do not work as bash interpreter
To execute any script which requires bash or shell scripting features, your need to execute that interpreter
To solve your problem you can follow below steps
1. Write your string into temp .sh file. Lets call it temp.sh
2. execute below using Runtime.getRuntime().exec
Process p = Runtime.getRuntime().exec("bash temp.sh");
bash will try to execute any command in temp.sh

How to invoke sh shell with file using Runtime.getRuntime().exec?

How to invoke sh file in linux terminal using Runtime.getRuntime().exec in java ?
I want to invoke the sh file in new terminal from java code. If i run it in terminal only it runs as a separate process, which will not be closed even if my programs exits. And thats why I'm not using ProcessBuilder, which stops the process invoked by it if the program using it exits.
If your script is marked as executable (chmod +x script.sh), you can invoke it by exec("./script.sh"). Otherwise you can directly call it using exec("sh script.sh").
Use:
Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", "sh myfile.sh" });
Since ProcessBuilder is just a thin wrapper around Runtime, using it directly will not do what you want.
Instead, you need to write a second script which creates a terminal window as a background process and detaches this process. General approach:
ProcessBuilder to start outer script
Outer script uses the Linux command nohup(1) to create a detached process for inner script. For example: `nohup xterm -e /bin/bash "script.sh &"
nohup cuts the connections between the new X terminal and the Java process. & sends the whole thing into the background, so the command doesn't until xterm exits.

Categories

Resources