Execute cmd commands from inside a java program - java

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

Related

Running/Sending CMD command in Java

I want to get rid of a .bat file in java and have the code post directly to CMD.
I have tried multiple variances of the below but i'm not getting it right.
The .bat file contains the following:
CD C:\"Program Files (x86)"\"UiPath Platform"\UIRobot.exe -file C:\ProgramData\UiPath\Projects\DM9\Main.xaml
I would like Java to post this directly to CMD instead.
Currently my code looks like:
String test = in.readUTF();
if (test.equals("Start"))
{
String[] command = {"cmd.exe", "/C", "Start", "C:Unipath\\start.bat"};
Process child = Runtime.getRuntime().exec(command);
}
Any advice?
Thanks in advance.
You haven't actually specified the problem, but I can run a batch file no problem without the cmd.exe argument. i.e. batch file
echo off
echo %1
can be run using
String[] command = {"test.bat", "HELLO"};
Process proc = Runtime.getRuntime().exec(command);
So I suspect your problem lies either with the cmd.exe argument or with the fact that your batch command doesn't seem to be valid
CD C:\"Program Files (x86)"\"UiPath Platform"\UIRobot.exe -file C:\ProgramData\UiPath\Projects\DM9\Main.xaml
Is this a Change Directory command with three arguments, a filename, a -file then another filename. Have you tested the batch file by itself?
Refer to this link for detailed example: Run Dos commands using JAVA
Courtesy of #akshay-pethani's answer in below question.
How do I execute Windows commands in Java?

Check if jar is running or not

I would like to check whether a jar of mine is running on the users system, to then relaunch if it is closed.
I am aware of the command jps -l which makes it possible to check the current running jars. Only problem is that for that line to work, it requires the user to have a JDK installed. So I was then wondering whether or not there is an equivalent to the jps -l line, which doesn't need a JDK or anything, but just checks whether a specific jar is running.
In the past I have also used the line cmd /c tasklist for Windows and the line top -F -R -o cpu for Mac. To check whether an app or exe was running, but that doesn't really seem to be working. When running the tasklist line on Windows and I then check for an exe called "myApp", it doesn't find it. Even though it might be running. Otherwise this would have been a perfect method, to check for a running app, exe or jar.
Here is an example code of how I tried to use the tasklist command to check for a specific executable.
try {
String procss;
Process pRun = Runtime.getRuntime().exec("cmd /c tasklist");
BufferedReader input = new BufferedReader(new InputStreamReader(pRun.getInputStream()));
while ((procss = input.readLine()) != null) {
if(!procss.contains("myApp"))
{
//Runtime command to launch exe or app.
}
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
Basically I would like to just edit the code above, to have a command line, of which is able to actually check whether the exe, app or jar is running. Maybe there is an alternative to cmd /c tasklist and top -F -R -o cpu, which is able to get all processes running on a pc and not just .exe or .app
On windows, you could use the wmic command to get the command line parameters a program was launched with.
For example, using wmic process where "name like '%java%'" get commandline,processid (basically just means "get the PID and command line arguments of process with a name like java") gives me this output for a test program:
616
"C:\Program Files\Java\jre1.8.0_111\bin\javaw.exe" -jar "A:\Programmering\Java\Pong\out\artifacts\Pong_jar\Pong.jar"
As you can see, you can get the location of the jar file which is running (which you could then use to check if it's your program). In this case, I just launched it by double clicking the jar file, you may get different outputs if you launch it in a different way, but there should always be something you can use to identify the java process (like a main class or jar file).

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

How to run batch file with parameters in java?

I have created a jar file called test.jar under C:\jars. I have JAR file under the same location named run.bat and it contains the below code -
#echo off
set exec_path=C:\jars java -cp %exec_path%/test.jar; com.mycomp.myapp.MyProgram "%1"%*
#echo on
It is running successfully from command prompt with parameters.
Now I would like to run it from another JAVA program.
Please suggest.
Thanks!
I've encountered this issue before. The answer is that you have to run cmd.exe or bash or whatever shell you've got, then feed in the command to that process via the process input/output streams.
Process p = Runtime.getRuntime().exec("cmd");
p.getOutputStream().write("mybatch.bat\n");

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

Categories

Resources