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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/792024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:32:38  来源:igfitidea点击:

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

javaoutput-redirect

提问by Eric Schulman

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

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

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

采纳答案by John Feminella

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.

当然,处理您关心的任何异常。

回答by Andy White

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.

你在做什么看起来不错。如果您的命令只返回单个字符串,则不需要 while 循环,只需将 reader.readLine() 值存储在单个 String 变量中。

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

此外,您可能应该对这些异常做一些事情,而不仅仅是吞下它们。

回答by Azder

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

这是最好的方法。您也可以使用具有可变参数构造函数的ProcessBuilder,因此您可以保存一两行代码

回答by epeleg

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 waitForthe return value of your process.

在这里阅读文章:http: //www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html
据我了解,您应该首先阅读输出和错误流您执行的命令,然后才是waitFor您的进程的返回值。

回答by Mohd Naved

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.

如果您只想从 java 代码运行 uname 命令,最好使用 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

System Class可以给你以下信息

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

关键:价值观

--> os.version : 操作系统版本
--> os.name : 操作系统名称

--> os.arch : 操作系统架构

--> java.compiler : 您正在使用的编译器的名称

--> java.ext.dirs : 扩展目录路径

--> java.library.path : 加载时搜索库的路径

--> user.dir : 用户当前工作目录

--> user.name : 用户的账户名

--> java.vm.version : JVM 实现版本

--> java.vm.name : JVM 实现名称

--> java.home : Java安装目录

--> java.runtime.version : JVM 版本

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

(来源 - 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.

例如:如果我运行的是基于 Linux 的系统,比如说 Ubuntu,下面的命令会给我关于它的信息。

System.getProperty("os.name");