如何使用Java执行系统命令(linux / bsd) [英] How to execute system commands (linux/bsd) using Java

查看:154
本文介绍了如何使用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.

这篇关于如何使用Java执行系统命令(linux / bsd)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆