I want to execute an operating system command in Java, and then print out it's returned value. Like this:
This is what I am trying...
String location_of_my_exe_and_some_parameters = "c:\\blabla.exe /hello -hi";
Runtime.getRuntime().exec(location_of_my_exe_and_some_parameters);
I tried putting a System.out.print() on the beginning of my Runtime... line, but it failed. Because, apparently, getRuntime() returns a Runtime object.
Now, the problem is, when I execute the "blabla.exe /hello -hi" command in command line, I got a result like: "You executed some command, hurray!". But, in Java, I got nothing.
I tried putting the return value into a Runtime object, to an Object object. However, they both failed. How can I accomplish this?
Problem Solved - this is my solution
Process process = new ProcessBuilder(location, args).start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
Notice that Runtime.exec(...) returns a Process object. You can use this object to capture its input stream and retrieve whatever it prints to the standard output:
Process p = Runtime.getRuntime().exec(location_of_my_exe_and_some_parameters);
InputStream is = p.getInputStream();
// read process output from is
You can capture the output of a command using this:
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
log.info(line);
}
//This will wait for the return code of the process
int exitVal = pr.waitFor();
UseProcessBuilder instead of Runtime.
Like:
Process process = new ProcessBuilder("c:\\blabla.exe","param1","param2").start();
Answer:
Process process = new ProcessBuilder("c:\\blabla.exe","/hello","-hi").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:", Arrays.toString(args));
Related
I want to run a python script(tensorflow's Image label script) after RPi's camera module captures a photo using a jar file. I have tried both Runtime and ProcessBuilder, but it says no file or Directory found.
Here's my Code for the Runtime Code:
Process rt = Runtime.getRuntime().exec("python3 -m scripts.image-label.py");
rt.waitFor();
BufferedReader in = new BufferedReader(new InputStreamReader(rt.getInputStream()));
String read = in.readLine();
ML = read;
result resfin = new result();
resfin.setVisible(true);
And here's the code for my ProcessBuilder one:
ProcessBuilder builder = new ProcessBuilder("/home/pi/Desktop/ML/scripts/image-label.py");
Process np = builder.start();
np.waitFor();
BufferedReader in = new BufferedReader(new InputStreamReader(np.getInputStream()));
String read = in.readLine();
ML = read;
result resfin = new result();
resfin.setVisible(true);
Am i doing something wrong? Or am i missing something? Any help would be appreciated!
I have tried with the following code, it is working fine, though I have not tried with -m "module" flag, since I do not know how to create a module file in python.
Found some of the issues with code:
1. You need to pass python3 as an argument to process builder as shown below
2. Provide an absolute path for a python file.
3. You can use either of Runtime or ProcessBuilder without an issue.
// Process rt = Runtime.getRuntime().exec("python3 -m /Users/<user-name>/demo/JavaNotepad/src/main/java/com/mypython.py");
ProcessBuilder builder = new ProcessBuilder("python3", "-m", "/Users/<user-name>/demo/JavaNotepad/src/main/java/com/mypython.py");
Process rt = builder.start();
int exitCode = rt.waitFor();
System.out.println("Process exited with : " + exitCode);
BufferedReader in = new BufferedReader(new InputStreamReader(rt.getInputStream()));
BufferedReader err = new BufferedReader(new InputStreamReader(rt.getErrorStream()));
System.out.println("Python file output:");
String line;
BufferedReader reader;
if (exitCode != 0) {
reader = err;
} else {
reader = in;
}
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
I want to execute a python script from java.
The code is getting in to the python file but only executes first line of the file.
following is the code:
Process p = Runtime.getRuntime().exec("python "+dir+"/pyfiles/testfile.py");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
value = in.readLine();
after the first line nothing is executed.
what is the solution?
'dir' value is getting from
final String dir = System.getProperty("user.dir");
link to python file:
https://drive.google.com/file/d/1tvkFTM_Oo5gTS7FyzeNgoeY5DLitFQjD/view?usp=sharing
The problem seems, that you are only reading the first line of your BufferedReader. So change your code as follows:
Process p = Runtime.getRuntime().exec("python "+dir+"/pyfiles/testfile.py");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = in.readLine()) != null)
{
System.out.println(line);
}
it worked fine when I passed like this:
String cmd = "python2.7 "+dir+"/pyfiles/getGitFiles.py "+ownerVal+" "+repoVal+" "+folderVal+" "+branchVal+" "+Values.accessToken;
System.out.println(cmd);
Process p = Runtime.getRuntime().exec(cmd);
passing the arguments inside the 'exec' itself is causing the problem.
I executed this code:
Process proc = Runtime.getRuntime().exec("cat /home/uhf/metrics.sh");
System.out.println(proc.toString());
String proc1 = proc.toString();
But I am not able to get the content of kafka_metrics.sh. Instead I am getting java.lang.UNIXProcess#5fd0d5ae as output. What should I include so that I can get the content of that file?
May this is what you are looking for.
Process proc = Runtime.getRuntime().exec("cat /home/uhf/metrics.sh");
String s = null;
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");
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);
}
You are printing the Process object.
to get the content of the executed process you need to take the input stream and pass that stream to the reader
Process process = Runtime.getRuntime().exec("cat /home/uhf/metrics.sh");
InputStream is = process.getInputStream();
try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
br.lines().forEach(System.out::println);
}
I have a class file say, abc.class which got compiled from abc.java
While trying to execute this java program, I am not getting the output in my console.
I have executed this file in linux environment.
the file contains one of the line which draws importance :
Runtime rt = Runtime.getRuntime();
String a = "ls";
Process proc = null;
try {
proc = rt.exec(a);
}
Note : While executing the program, the prompt is not there and i think that might be the reason for 'ls' not getting executed through my program. I am not getting any error though.
I am concern that as soon as the file get execute I will get the list of file in the prompt.
Hope i make to clear you all guys about my issue.
Please can I have any input on this issue of mine. your valuable
Your command should be executed ,but your output is not printed as by default output will be not directed to your console , for getting output on your console, you just need to take input stream from your process and need to read it.
Runtime rt = Runtime.getRuntime();
String a = "ls";
Process proc = null;
try
{
proc = rt.exec(a);
proc.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line=" ";
while((line=reader.readLine())!=null)
{
output.append(line+"\n");
}
}
This works:
Runtime rt = Runtime.getRuntime();
String a = "/bin/ls";
Process proc = rt.exec(a);
proc.waitFor();
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader( is );
BufferedReader br = new BufferedReader( isr );
String line;
while( (line = br.readLine() ) != null ){
System.out.println( line );
}
br.close();
// to see errors:
System.out.println( "*** error output ***" );
InputStream isErr = proc.getErrorStream();
InputStreamReader isrErr = new InputStreamReader( isErr );
BufferedReader brErr = new BufferedReader( isrErr );
String line;
while( (line = brErr.readLine() ) != null ){
System.out.println( line );
}
brErr.close();
in my java program, i am trying to get the InputStream from a process and print it with this piece of code:
try {
Process p = Runtime.getRuntime().exec("cmd /c start dammage\\4.simulation.cmd");
//BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
//StringBuffer sb = new StringBuffer();
//String line;
//while ((line = br.readLine()) != null) {
//sb.append(line).append("\n");
//}
//System.out.println(sb.toString());
String input = IOUtils.toString(p.getErrorStream());
System.out.println(input);
} catch (IOException ex) {
Logger.getLogger(UI.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(this, "Something happened");
}
I tried both ways shown above (commented and uncommented), but none of them prints anything. So i would like to ask what am i doing wrong here?
I appreciate any help.
The buffered reader solution looks fine. You might be looking in the wrong stream. Try getting from both streams.. Like
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
StringBuffer sb = new StringBuffer();
String line;
//Read the output from the command
while ((line = stdInput.readLine()) != null) {
sb.append(line).append("\n");
}
//read any errors from the attempted command
while ((line = stdError.readLine()) != null) {
sb.append(line).append("\n");
}
Are you sure it should print something? Because, the commented code should work just right provided the command executed is returning non-empty input stream. Try replacing the argument of exec to "cmd". And see if it's able to read from the input stream. Do following. On windows machine it should give you welcome message from cmd (the usual welcome message we get after we run start command prompt).
Process p = Runtime.getRuntime().exec("cmd");
About the uncommented code, How IOUtils work? Does it read from the error stream repeatedly. Because, IMO, it's just one time read and not the repetitive one.
Hope I don't confuse.
You should add a p.waitFor(); to give the program time to terminate. Also, verify if you really want to read stdout or stderr
This works for me:
Process p = Runtime.getRuntime().exec("cmd /c java -version");
int ret = p.waitFor();
System.out.println("process terminated with return code: " + ret);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
StringBuffer sb = new StringBuffer();
String line;
while((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
System.out.println(sb.toString());