How to execute system commands (linux/bsd) using Java

Viewed 80925

I am attempting to be cheap and execute a local system command (uname -a) in Java. I am looking to grab the output from uname and store it in a String. What is the best way of doing this? Current code:

public class lame {

    public static void main(String args[]) {
        try {
            Process p = Runtime.getRuntime().exec("uname -a");
            p.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line=reader.readLine();

            while (line != null) {    
                System.out.println(line);
                line = reader.readLine();
            }

        }
        catch(IOException e1) {}
        catch(InterruptedException e2) {}

        System.out.println("finished.");
    }
}
5 Answers

Your way isn't far off from what I'd probably do:

Runtime r = Runtime.getRuntime();
Process p = r.exec("uname -a");
p.waitFor();
BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";

while ((line = b.readLine()) != null) {
  System.out.println(line);
}

b.close();

Handle whichever exceptions you care to, of course.

That is the best way to do it. Also you can use the ProcessBuilder which has a variable argument constructor, so you could save a line or two of code

What you are doing looks fine. If your command is only returning a single string, you don't need the while loop, just store the reader.readLine() value in a single String variable.

Also, you probably should do something with those exceptions, rather than just swallowing them.

I know this questionis very old, but I just wanted to add some information that might come handy to some people.

If you just want to run uname command from java code, better use the System class to get information about the system.

It will not only remove the dependency of running the terminal command, but it will also work independently of the Operating System.

System Class can give you the following information

Keys : Values

--> os.version : OS Version
--> os.name : OS Name

--> os.arch : OS Architecture

--> java.compiler : Name of the compiler you are using

--> java.ext.dirs : Extension directory path

--> java.library.path : Paths to search libraries whenever loading

--> user.dir : Current working directory of User

--> user.name : Account name of User

--> java.vm.version : JVM implementation version

--> java.vm.name : JVM implementation name

--> java.home : Java installation directory

--> java.runtime.version : JVM version

(Source - https://www.geeksforgeeks.org/getproperty-and-getproperties-methods-of-system-class-in-java/)

ex : If I am running a Linux based system, Say Ubuntu, the following command will give me the information about it.

System.getProperty("os.name");
Related