How to print command line execution output using java - java

While running below code prompt will open and it will show java version information. I want to print that java version information. please help me on this
public class Test {
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd.exe /c start cmd.exe /k \"java -version\"");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
}
}

At the moment you read the stream the process might not actualy be done yet. I'm pretty sure you first have to wait int exitVal = proc.waitFor(); on the process to finish before reading the outputStream.
for debugging wrapping part of this in a try with logging on the proc.getErrorStream() might help to

Related

How can i open an hidden cmd in java and then write on it commands?

What i want to do is open a new cmd as the application starts and then write on it different commands in different moments.
Example: i start my application, it runs a new cmd that is hidden so it can't be seen, and then it writes "cd ..", the application wait ten seconds(for example) and then it writes "cd .." another time and finally it writes "dir" and it prints out the results of 'dir' command.
I've tryed to use this code to do that
public static void main(String[] args) throws IOException{
Runtime rt = Runtime.getRuntime();
Process process = rt.exec("cmd /c cd .. ");
process = rt.exec("cmd /c cd .. ");
process = rt.exec("cmd /c dir");
BufferedReader commReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while((line = commReader.readLine()) != null){
System.out.println(line);
}
}
but as i've seen it doesn't work because it runs command on different cmds.
So sorry for my terrible english and does anyone know how to solve that?
You are overwriting your process variable so of course it's going to execute multiple instances of cmd.
What you need to do is open a single process and then write commands to its OutputStream which is connected to the normal input of the sub-process.
public static void main(String[] args) throws IOException {
ProcessBuilder builder = new ProcessBuilder("cmd");
Process process = builder.start();
OutputStream stdin = process.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
writer.write("cd ..\n");
writer.write("dir\n");
writer.flush();
writer.close();
BufferedReader commReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while((line = commReader.readLine()) != null){
System.out.println(line);
}
}

Execute external Java code and get output

I want to execute a Java CLI-program from within another Java program and get the output of the CLI-program. I've tried two different implementations (using runtime.exec() and ProcessBuilder) and they don't quite work.
Here's the peculiar part; the implementations work (catch the output) for when executing commands such as pwd but for some reason they do not catch the output of a Hello World java program executed with java Hello.
Execution code:
public static void executeCommand(String command)
{
System.out.println("Command: \"" + command + "\"");
Runtime runtime = Runtime.getRuntime();
try
{
Process process = runtime.exec(command);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(process.getErrorStream()));
// read the output from the command
System.out.println("Standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
Example output
Command: "cd /Users/axelkennedal/Desktop && java Hello"
Standard output of the command:
Standard error of the command (if any):
Command: "pwd"
Standard output of the command:
/Users/axelkennedal/Dropbox/Programmering/Java/JavaFX/Kode
Standard error of the command (if any):
I have verified that Hello does indeed print "Hello world" to the CLI when running Hello directly from the CLI instead of via executeCommand().
Hello world
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello world!");
}
}
This "cd /Users/axelkennedal/Desktop && java Hello" is not one command but two commands separated by the &&. In general it means do the first command and if the first command succeeds do the second command. You can't pass this as a single command but you can implement the logic yourself:
eg to execute "cmd1 && cmd2"
if (Runtime.getRuntime().exec("cmd1").waitFor() == 0) {
Runtime.getRuntime().exec("cmd2").waitFor();
}
However, because in this case cmd1 is to change directories there is a better way, which is to use the directory function of ProcessBuilder instead of the first command.
Process p = new ProcessBuilder("java","hello")
.directory(new File("/Users/axelkennedal/Desktop"))
.start();

How to I exit a while loop after starting a process in Java?

Just found this post (and found the code which I'm also pasting below):
java runtime.getruntime() getting output from executing a command line program
My question is, how do I kill the process? It seems that the code blocks in the while loop. I've tried several options like using a boolean, running all the code in a separate thread and stuff like this, but without any success.
I just want to start an Android emulator and kill it whenever I want.
Runtime rt = Runtime.getRuntime();
String[] commands = {"emulator", "-avd", "jenkins",
"-scale", "96dpi", "-dpi-device", "100"};
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
Okay.
Use below code to get The Process ID of that current running thread or Process.
String processName =java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
String ProcessID = processName.split("#")[0];//Process Id
Use that Process ID to kill that Process in your CPU.
I think for that purpose you may wish to write any other trigger or any condition in While loop.

Executing a python script inside java map reduce

I need to execute a python script inside a java mapreduce program.
Here, in the mapper class , I need execute the the python command :
python methratio.py --ref=../refernce/referncefile -r -g --out=Ouputfile ./Inputfile
Here the Inputfile is the input file in hdfs and the outputfile (in hdfs) is where the python script writes the ouput.
Can I use process builder or any other better options are there ??
I don't know if this can help you, but you can execute system commands in this way in java:
public static void main(String[] args) throws IOException {
String s = null;
String command = "python <your_command>";
Process p = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
}
You can see a detailed example in http://alvinalexander.com/java/edu/pj/pj010016
Hope this help you :D

runtime.exec() taking infinite time to execute code

I want to execute a command which takes 2 arguments.
1.input file name
2.output file name.
The command is sixV1.1 outputFile.txt
The code is:
String cmd= "sixV1.1 <inputFile.txt >outputFile.txt";
Process p=Runtime.getRuntime().exec(cmd);
int retValue=p.waitFor();
when the i run above code,it is taking infinite time.
Is it possible to give <, > charecters in cmd .Please suggest me....
The right way to do input/output redirection when you start a process in Java is to write/read from the process's streams:
Process p = Runtime.getRuntime().exec("sixV1.1");
InputStream is = p.getInputStream();
// read from is and write to outputFile.txt
OutputStream os = p.getOutputStream();
// read from inputFile.txt and write to os
There's a fantastic blog post by Michael C. Daconta about successful command line calls using Runtime in Java. It's not as easy as you might think!
The following code extract from that blog post describes "MediocreExecJava", a class that successfully runs a program using Runtime.exec() and manages its input and output without hanging. I've used it before and it works. I highly recommend reading the post to understand why!
import java.util.*;
import java.io.*;
public class MediocreExecJavac
{
public static void main(String args[])
{
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("javac");
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<ERROR>");
while ( (line = br.readLine()) != null)
System.out.println(line);
System.out.println("</ERROR>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
}
}

Categories