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

查看:34
本文介绍了如何使用 Java 执行系统命令 (linux/bsd)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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天全站免登陆