Error on Runtime.getRuntime().exec - java

I have issue using Runtime.getRuntime().exec
String line = "";
String output = "";
Process p = Runtime.getRuntime().exec(new String[]{"dmidecode | grep UUID:"});
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
output += (line + '\n').trim();
}
input.close();
I test this and is not working
String line = "";
String output = "";
Process p = Runtime.getRuntime().exec("dmidecode | grep UUID");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
output += (line + '\n').trim();
}
input.close();
I get the next error on linux machine:
java.io.IOException: Cannot run program "dmidecode | grep UUID:": error no such file or directory
But I test the command in the console and I get the result!
dmidecode | grep UUID:=> UUID: 564DAF5F-FBF7-5FEE-6BA4-67F0B12D8E0E
How to get the same result using a Java based Process?

The pipe operator | wont work as this is part of the command shell. Try using a shell to execute the command. Also you may want to use ProcessBuilder for its convenience
ProcessBuilder builder =
new ProcessBuilder("bash", "-c", "dmidecode | grep UID:");
builder.redirectErrorStream(true);
Process p = builder.start();

Related

Java program not getting output from terminal

I am running my Java program from terminal and I am trying to count the number of files in a certain directory using a linux command in my code; I have managed to get output for all other commands but this one.
My command is: ls somePath/*.xml | wc -l
When I run my command in my code, it appears that it has nothing to output, yet when I run the same exact command in terminal it works just fine and actually outputs the number of xml files in that directory.
Here is my code:
private String executeTerminalCommand(String command) {
String s, lastOutput = "";
Process p;
try {
p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
System.out.println("Executing command: " + command);
while ((s = br.readLine()) != null){//it appears that it never enters this loop since I never see anything outputted
System.out.println(s);
lastOutput = s;
}
p.waitFor();
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
return lastOutput;//returns empty string ""
}
Updated code w/ output
private String executeTerminalCommand(String command) {
String s, lastOutput = "";
try {
Process p = new ProcessBuilder().command("/bin/bash", "-c", command).inheritIO().start();
//Process p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
System.out.println("Executing command: " + command);
while ((s = br.readLine()) != null){
System.out.println("OUTPUT: " + s);
lastOutput = s;
}
System.out.println("Done with command------------------------");
p.waitFor();
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("LAST OUTPUT IS: " + lastOutput);
return lastOutput;
}
output:
Executing command: find my/path -empty -type f | wc -l
Done with command------------------------
1
LAST OUTPUT IS:
To execute a pipeline, you have to invoke a shell, and then run your commands inside that shell.
Process p = new ProcessBuilder().command("bash", "-c", command).start();
bash invokes a shell to execute your command and -c means commands are read from string. So, you don't have to send the command as an array in ProcessBuilder.
But if you want to use Runtime then
String[] cmd = {"bash" , "-c" , command};
Process p = Runtime.getRuntime().exec(cmd);
Note: You can check advantages of ProcessBuilder here and features here over Runtime

How to run a terminal command and print the output through java in Mac

I tried below code to get the output of the ran command. But it printing empty.
String cmd = "/bin/bash device_id -l";
Process process = Runtime.getRuntime.exec(cmd);
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
Could anyone please help me. I have to get the connected iDevice UDID.
With the below code I could get the connected device udid.
public String deviceUDID() throws IOException{
ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c", "/usr/local/bin/idevice_id -l");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
line = r.readLine();
System.out.println(line);
return line;
}

Find the process information with top command in java

I want to get the process information using the top command. I have the below code but it is not working, it just exists the program without any output. My goal is to get the process name, process ID, and memory usage, but that's the later part. For now, I am stuck in getting process information using the top command in Java using grep.
public void getProcessInfo(String processName) {
Runtime rt = Runtime.getRuntime();
try {
String[] cmd = { "/bin/sh", "-c", "top | grep " + processName };
Process proc = rt.exec(cmd);
InputStream stdin = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace(e);
}
}
This question has been asked and answered many times before:
In normal mode the top command does not output to stdout, which is why you cannot simply pipe its output into another CLI utility as you try to do. Instead you have to switch the command to "batch mode" by using the -b flag. In addition you have to limit the number of iterations to a single if you want to process the result (no sense for further iterations in non interactive mode):
top -b -n 1 | grep "whatever"
This is documented on the commands man page: man top
Have fun with your project!
Runtime.exec is obsolete. Use ProcessBuilder instead.
You can make your task considerably easier by avoiding the use of grep, or any piping, altogether. Who needs grep when you have Java?
Building on arkascha's answer, you could do:
String processLine = null;
ProcessBuilder builder = new ProcessBuilder("top", "-b", "-n", "1");
Process proc = builder.start();
try (BufferedReader stdin = new BufferedReader(
new InputStreamReader(proc.getInputStream()))) {
String line;
while ((line = stdin.readLine()) != null) {
if (line.contains(processName)) { // No need for grep
processLine = line;
break;
}
}
}
You probably want to skip the summary information and header line:
String processLine = null;
ProcessBuilder builder = new ProcessBuilder("top", "-b", "-n", "1");
Process proc = builder.start();
try (BufferedReader stdin = new BufferedReader(
new InputStreamReader(proc.getInputStream()))) {
String line;
// Blank line indicates end of summary.
while ((line = stdin.readLine()) != null) {
if (line.isEmpty()) {
break;
}
}
// Skip header line.
if (line != null) {
line = stdin.readLine();
}
if (line != null) {
while ((line = stdin.readLine()) != null) {
if (line.contains(processName)) { // No need for grep
processLine = line;
break;
}
}
}
}

How can I run command from Java code and read the output?

I am writing a code to execute a command and reading the output
If I run the command on command prompt, it looks like this
Command is
echo 'excellent. awesome' | java -cp "*" -mx5g edu.stanford.nlp.sentiment.SentimentPipeline -stdin
Command produces multi line output. How can I print this output in my java code?
I have written following code, but it produces output as command itself that is
echo 'excellent. awesome' | java -cp "*" -mx5g edu.stanford.nlp.sentiment.SentimentPipeline -stdin
rather than actual command output as we can see it in the screenshot
final String cmd = "java -cp \"*\" -mx5g edu.stanford.nlp.sentiment.SentimentPipeline -stdin";
final String path = "C:/Project/stanford-corenlp-full-2015-01-29/stanford-corenlp-full-2015-01-29";
String input = "excellent";
String cmdString = "echo '" +input + "' | " + cmd;
Process process = Runtime.getRuntime().exec(cmdString,null, new File(path));
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
Try using ProcessBuilder:
try {
ProcessBuilder pb = new ProcessBuilder("your command here");
pb.redirectErrorStream(true);
Process p = pb.start();
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader( is ) );
while ((line = br.readLine()) != null) {
System.out.println(line);
}
p.waitFor();
} catch (InterruptedException e) {
//handle exception
}

Get output from BAT file using Java

I'm trying to run a .bat file and get the output. I can run it but I can't get the results in Java:
String cmd = "cmd /c start C:\\workspace\\temp.bat";
Runtime r = Runtime.getRuntime();
Process pr = r.exec(cmd);
BufferedReader stdInput = new BufferedReader(
new InputStreamReader( pr.getInputStream() ));
String s ;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
The result is null. No idea why I get this. Note that I'm using Windows 7.
Using "cmd /c start [...]" to run a batch file will create a sub process instead of running your batch file directly.
Thus, you won't have access to its output.
To make it work, you should use:
String cmd = "C:\\workspace\\temp.bat";
It works under Windows XP.
You need to start a new thread that would read terminal output stream and copy it to the console, after you call process.waitFor().
Do something like:
String line;
Process p = Runtime.getRuntime().exec(...);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
Better approach will be to use the ProcessBuilder class, and try writing something like:
ProcessBuilder builder = new ProcessBuilder("/bin/bash");
builder.redirectInput();
Process process = builder.start();
while ((line = reader.readLine ()) != null) {
System.out.println ("Stdout: " + line);
}
BufferedReader stdInput = new BufferedReader(new
InputStreamReader( pr.getErrorStream() ));
instead use
BufferedReader stdInput = new BufferedReader(new
InputStreamReader( pr.getInputStream ));

Categories

Resources