2

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Chacaman
  • 51
  • 1
  • 9
  • Read (and implement) *all* the recommendations of [When Runtime.exec() won't](http://www.javaworld.com/jw-12-2000/jw-1229-traps.html). That might solve the problem. If not, it should provide more information as to the reason it failed. Then ignore that it refers to `exec` and build the `Process` using a `ProcessBuilder`. Also break a `String arg` into `String[] args` to account for arguments which themselves contain spaces. – Andrew Thompson Aug 31 '13 at 02:08
  • possible duplicate of [How to use Pipe Symbol through exec in Java](http://stackoverflow.com/questions/7226538/how-to-use-pipe-symbol-through-exec-in-java) – Stephen C Aug 31 '13 at 03:19

1 Answers1

2

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();
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • Almost correct, but the "-c" option's argument needs to be a single string; i.e. `"bash", "-c", "dmidecode | grep UID:" – Stephen C Aug 31 '13 at 03:18