Runtime.getRuntime().exec("ipconfig") 的用法

发布时间 2023-06-14 17:06:49作者: JAVA_织梦者_TW

 `Runtime.getRuntime().exec()` 是Java中的一个方法,可以在Java程序中执行外部程序。这个方法返回一个 `Process` 对象,可以用于控制和查看执行的外部程序。

`exec()` 方法有多个重载版本,可以传递不同的参数来控制执行的外部程序。例如:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ExecExample {
    public static void main(String[] args) {
        try {
            // Execute a command
            Process process = Runtime.getRuntime().exec("command");

            // Get the output of the command
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // Wait for the command to finish
            int exitCode = process.waitFor();
            System.out.println("Exited with error code: " + exitCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

```java
// 执行命令行命令
Process p = Runtime.getRuntime().exec("cmd /c dir");

// 执行可执行文件并传递参数
Process p = Runtime.getRuntime().exec("myapp.exe arg1 arg2");

// 执行Python脚本并传递参数
Process p = Runtime.getRuntime().exec("python myscript.py arg1 arg2");
```

在以上例子中,我们分别执行了一个Windows的命令行命令、一个C++可执行文件、以及一个Python脚本并传递了参数。执行后,`exec()` 方法会返回一个 `Process` 对象,可以通过这个对象的 `getInputStream`、`getOutputStream` 和 `getErrorStream` 方法来获取外部程序的输出流、输入流和错误流。

```java
InputStream in = p.getInputStream();
OutputStream out = p.getOutputStream();
InputStream error = p.getErrorStream();
```

使用这些流,我们可以读取外部程序的输出和错误信息,或将输入数据写入到外部程序中。

需要注意的是,在使用 `exec()` 方法时,需要小心防范一些安全问题,例如传递恶意命令、执行可疑程序等,要避免这些安全问题,可以使用 `ProcessBuilder` 类来代替 `Runtime.getRuntime().exec()` 方法。