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

2019-01-01 07:17发布

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.");
    }
}

4条回答
弹指情弦暗扣
2楼-- · 2019-01-01 07:52

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.

查看更多
只若初见
3楼-- · 2019-01-01 07:53

I know this is very old but still...

Reading the article here: http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html
It is my understanding that you should first read the output and error streams of your executed command and only then waitFor the return value of your process.

查看更多
ら面具成の殇う
4楼-- · 2019-01-01 08:00

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.

查看更多
无色无味的生活
5楼-- · 2019-01-01 08:03

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

查看更多
登录 后发表回答