For some terminal commands, they repeatedly output. For example, for something that's generating a file, it may output the percent that it is complete.
I know how to call terminal commands in Java using
Process p = Runtime.getRuntim().exec("command goes here");
but that doesn't give me a live feed of the current output of the command. How can I do this so that I can do a System.out.println() every 100 milliseconds, for example, to see what the most recent output of the process was.
You need to read InputStream from the process, here is an example:
Edit I modified the code as suggested here to receive the errStream with the stdInput
ProcessBuilder builder = new ProcessBuilder("command goes here");
builder.redirectErrorStream(true);
Process process = builder.start();
InputStream is = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
For debugging purpose, you can read the input as bytes instead of using readLine just in case that the process does not terminate messages with newLine
Related
I'm trying to execute a script via JAVA code, but it's not being executed. I tried execute() of Process class but later switched to ProcessBuilder after some searching hoping to make this work. But the script's not getting executed.
JAVA Code:
String fileName = "pkgdiff.sh";
File file = new File(fileName);
ProcessBuilder builder = new ProcessBuilder("/bin/sh", fileName);
builder.directory(file.getParentFile());
Process process = builder.start();
process.waitFor();
StringBuffer output = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
LOGGER.info("### Script Execution result --> " + fileName+"-->" + output);
Script file:
#!/bin/sh
.. rest of the content
How much output is the script producing? You should be processing its output before you call waitFor(), otherwise the process might block if it fills up its output buffer.
From the Java API:
Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock.
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.
i'm trying to execute a command with root privileges, i try this(only for example):
Process process = Runtime.getRuntime().exec(new String[]{"su","-c","whoami"});
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
result += line;
Log.d(TAG,"RESULT:"+result);
}
But i need to call it in a cicle with hundred times, so this way is very slow and always is showing a dialog with the message of the root privileges are granted, so how i can create a sigle su process for write and read consecutively using input and output streams? i know to use both but i dont know how to write and the read the result of the command. Thanks for your help.
I want to know the owner of current process in Unix using Java. I want to find the current server's owner name. I tried with running "who am i" command in Runtime.getRuntime().exec(), but its not returning me any results.
String line = "";
Process p = Runtime.getRuntime().exec("who am i");
InputStream iStream = p.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(iStream);
BufferedReader bufReader = new BufferedReader(inputStreamReader);
while ((line = bufReader.readLine()) != null) {
System.out.println("Input "+line);
}
Is there anything wrong with this code or any idea how can I find the owner of current process using Java?
First thing, I think System.getProperty("user.name") should work for that
Second thing, the reason your code is not returning anything is because the command is whoami with NO SPACES so your exec line should be (assuming you are running on windows through cygwin or on a **nix based system)
Process p = Runtime.getRuntime().exec("whoami");
I have the following code in java that calls the date command in the command prompt:
// prepare command prompt runtime and process
Runtime runtime = null;
Process process = null;
// prepare output stream
OutputStream outputStream = null;
try {
runtime = Runtime.getRuntime(); // instantiate runtime object
process = runtime.exec("date"); // get the current date in command prompt
// read the output of executing date command
outputStream = process.getOutputStream();
// output the date response
System.out.println(outputStream);
process.waitFor(); // wait for the date command to finish
} catch(Exception e) {
e.printStackTrace();
} // end catch
How can I read the outputStream value for me to be able to use the System.output.println()
You don't read the output stream, you write to it to pass data to process. To read the data from process use
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
br.readLine();
The code is for string output of process. Of course if your process outputs data in other way you have to change the wrappers around process.getInputStream()
Update: I think it is in some way confusing that we use getInputStream to actually read process output :) The reason is that initially basic classes OutputStream and InputStream were named so relatively to the code that uses them (the code you write). So when you use OutputStream you actually use it as output for your program. When you use process.getOutputStream you don't get process' output but instead get your program output which is piped to process input. When you use process.getInputStream you get input for your program which obtains data piped from process' output.
you can do like this way without using OutputStream object
Process p = Runtime.getRuntime().exec("date");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
String answer = sb.toString();
System.out.println(answer);