r3dsm0k3 r3dsm0k3 - 9 months ago 35
Java Question

Execute Unix system command from JAVA problem

I am facing a weird issue with executing a system command from JAVA code.

Actually i want to get the

system information from my JAVA App.

For that im using

Runtime.getRuntime().exec("system_profiler -detailLevel full");

This is working fine.If i print the output,it is cool.
But i want to write this information to a
file for future use.For that im using the -xml argument of

String cmd = "system_profiler -detailLevel full -xml > "+System.getProperty( "user.home" )+"/sysinfo.plist";
Process p = Runtime.getRuntime().exec(cmd);

Basically this should create a plist file in the current users home directory.

But this seems to be not writing anything to file.

Am i missing something here ?


My Java is more than rusty, so please be gentle. ;-)

  1. Runtime.exec() does not automatically use the shell to execute the command you passed, so the IO redirection is not doing anything.

  2. If you just use:

    "/bin/sh -c system_profiler -detailLevel full > path/file.plist"

    Then the string will be tokenized into:

    { "/bin/sh", "-c", "system_profiler", "-detailLevel", "full", ">", "path/file.plist" }

    Which also wouldn't work, because -c only expects a single argument.

Try this instead:

String[] cmd = { "/bin/sh", "-c", "system_profiler -detailLevel full > path/file.plist" };
Process p = Runtime.getRuntime.exec(cmd);

Of course, you could also just read the output of your Process instance using Process.getInputStream() and write that into the file you want; thus skip the shell, IO redirection, etc. altogether.