Java Execute an external program and capture the output - java

So i try to Execute an external program and capture the output.
Currently the part that execute command works fine (using .bat file) and i can see the output on the cmd window.
The part that need to read the output not and it seemt that it stack inside my while
This is what i have try:
String[] command = {"cmd.exe", "/C", "Start", "d:\\batFile.bat"};
Process process = Runtime.getRuntime().exec(command);
InputStream is = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
Update
This is my .bat file:
docker volume create --name=mydb
timeout 3
docker run -d -p 27017:27017 -v mydb:/data/db mongo
timeout 3

Maybe you can try to redirect the output like this :
Process runtimeProcess1;
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C","Start","d:\\batFile.bat");
pb.redirectOutput(Redirect.INHERIT);
pb.redirectError(Redirect.INHERIT);
pb.redirectInput(Redirect.INHERIT);
runtimeProcess1 = pb.start();
int processComplete1 = runtimeProcess1.waitFor();

Related

Start filebeat using a Java code?

I'm using filebeat to read some log files and I need to start filebeat using a Java program. And the filebeat commands are executed using the Windows PowerShell. I used the following code but it didn't work.
try {
ProcessBuilder b1 = new ProcessBuilder("powershell.exe", "/c", "cd \"C:\\Program Files\\Filebeat\" && ./filebeat -e -c filebeat.yml -d \"publish\"\\");
b1.redirectErrorStream(true);
Process p1 = b1.start();
BufferedReader r1 = new BufferedReader(new InputStreamReader(p1.getInputStream()));
String line1;
while (true) {
line1 = r1.readLine();
if (line1 == null) { break; }
System.out.println(line1);
}
} catch(Exception e) {
}
The below code worked.
ProcessBuilder pb = new ProcessBuilder("C:\\Program Files\\Filebeat\\filebeat.exe", "-c", "C:\\Program Files\\Filebeat\\filebeat.yml", "-e");
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
p.waitFor();
You're confusing PowerShell with CMD. The latter has a parameter /c, the former doesn't. Also, instead of using cd in the comandline you should simply set the working directory on the ProcessBuilder object, and each token of your commandline should be a separate array element.
Change your code to something like this and it should do what you expect:
ProcessBuilder b1 = new ProcessBuilder("cmd.exe", "/c", "filebeat", "-e", "-c", "filebeat.yml", "-d", "\"publish\"");
b1.directory(new File("C:\\Program Files\\Filebeat"));
b1.redirectErrorStream(true);
Process p1 = b1.start();

Executing custom Commands in Java

With this, we can execute "build in" commands in java. However if we want to run some custom commands from this, Changing "pwd" to "device_id -l" doesn't work. "device_id -l" should list all the ids of attached devices of currently host. if "device_id -l" is executed in terminal itself. it works fine. There is not a question for the "build in" bash commands. Thank you.
String cmd = "pwd";
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null)
System.out.println(line);
We can excuate
You can try using ProcessBuilder.
// create process
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "device_id", "-l");
// start process
Process p = pb.start();
// wait for process exit
p.waitFor();
// read process output
BufferedReader buf = new BufferedReader(newInputStreamReader(p.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null)
System.out.println(line);
You need to split your command+arguments to a String array. In your case, if you want to execute "device_id -l", split that into an array like this:
String[] cmd = new String[] {"/full/path/to/device_id", "-l"};
Process pr = Runtime.getRuntime().exec(cmd);
And, you might want to use ProcessBuilder.
String[] cmd = new String[] {"/full/path/to/device_id", "-l"};
ProcessBuilder pb = new ProcessBuilder(cmd);
Process pr = pb.start();
Finally, you'll have to take into account that Java does not look for executables in PATH (like command shell does), you'll have to provide full path to the executable/script that you want to execute (or it has to be in the working directory; you can set the working directory with ProcessBuilder.directory(File)).
See also: Difference between ProcessBuilder and Runtime.exec()

Java ProcessBuilder and bash

I am trying to execute a bash script from Java with ProcessBuilder
my code is :
Process createUser = buildProcess(
"/bin/su",
"-c",
"\"/opt/somedir/testdir/current/bin/psql",
"--command",
commandForUserCreation,
/* "'select * from users'", */
"--dbname",
"mydbname\"",
"myuser"
);
The problem is that I receive error:
/bin/su: unrecognized option '--dbname'
If I put echo in first place of my commands it prints correct command in bash and if I copy/paste this command it works!
Please, help me to resolve this issue.
You need to supply the whole command to execute by su as a single argument. Try this:
Process createUser = buildProcess(
"/bin/su",
"-c",
"/opt/vmware/vpostgres/current/bin/psql --command " + commandForUserCreation + " --dbname mydbname",
myuser
);
This is what I use in processBuilder:
String[] command = new String[] {"echo", "Hello"};
String workspace = "/bin/su";
System.out.println("Trying to run command: "+ Arrays.toString(command));
ProcessBuilder probuilder = new ProcessBuilder(command);
probuilder.directory(new File(workspace));
Process process = probuilder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:\n",Arrays.toString(command));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
I hope it helps.

How to execute terminal command in specific directory from java

I am trying to execute originate command in specific directory "/usr/local/freeswitch/bin", In bin I have to run executable file fs_cli by ./fs_cli command, In fs_cli I have to execute following command
originate loopback/1234/default &bridge(sofia/internal/1789)
Its working fine from terminal, The same command can be executed from bin
./fs_cli -x "originate loopback/1234/default &bridge(sofia/internal/1789)"
I tried folowing java program to do the above task
Process pr = Runtime.getRuntime().exec("./fs_cli -x \"originate loopback/1234/default &bridge(sofia/internal/1789#192.168.0.198)\"");
BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String str = null;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
I have creted symbolic link of fs_cli and placed in current location
The above program is showing following output
Output
-ERR "originate Command not found!
As far as I am concerned whwn above command is working fine with terminal it should be the same from java, So it shows I am wrong somewhere
Please help me to sort out this problem.
Use ProcessBuilder and supply a directory path
ProcessBuilder pb = new ProcessBuilder(
"./fs_cli",
"-x",
"originate loopback/1234/default &bridge(sofia/internal/1789#192.168.0.198)");
pb.directory(new File("..."));
Process pr = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String str = null;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
Where possible, you should provide the command arguments as separate Strings, this will pass each as a separate argument to the process and take care of those arguments that need to be escaped by quotes for you (unless it's expecting the quotes, then you should include them anyway)
The other way is:
ProcessBuilder processBuilder = new ProcessBuilder( "/bin/bash", "-c", "cd /usr/local/freeswitch/bin && ./fs_cli -x \"originate loopback/1234/default &bridge(sofia/internal/1789)\"" );
processBuilder.start();

How to run unix enq command in java program

Here is the unix command for adding a file to the queue.
enq -P QueueName:PrinterName FileName
Is it possible to run the above command using java.
Yes, it's possible using ProcessBuilder:
ProcessBuilder builder =
new ProcessBuilder("enq", "-P", "QueueName", "FileName");
Process process = builder.start();
InputStreamReader streamReader = new InputStreamReader(process.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
See: enq syntax
Process p = Runtime.getRuntime().exec(new String[]{"enq", "-P", "QueueName:PrinterName FileName"});

Categories