如何使用Java执行系统命令(linux / bsd)

如何使用Java执行系统命令(linux / bsd)

问题描述:

我试图廉价并在Java中执行本地系统命令( uname -a )。我希望从 uname 中获取输出并将其存储在String中。这样做的最佳方式是什么?当前代码:

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


您的方式离我可能做的不远:

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.