【问题标题】:Java Runtime.getRunTime().exec(CMD) not supporting pipesJava Runtime.getRunTime().exec(CMD) 不支持管道
【发布时间】:2012-10-14 08:23:52
【问题描述】:

我正在尝试编写一个程序,该程序将显示并能够使用 JFrame 窗口更新您的 IP 地址设置。我正在寻找纯粹在 Windows 上运行它,所以我试图能够使用 netsh windows 命令来检索/设置详细信息。

windows 命令: netsh interface ip show config name="Local Area Connection" | Find "IP" 完全返回我想要的,但是我编写的代码无法通过管道运行,只有在我写到“本地连接”部分时它才会起作用。

有没有什么方法可以使用管道功能来专门返回 IP 地址?我读到您可以将行作为字符串数组传递,即 String[] cmd = netsh........

package ipchanger;

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

public class test {

    private String CMD;

public void executecommand(String CMD) {
        this.CMD = CMD;

        try {
            // Run whatever string we pass in as the command
            Process process = Runtime.getRuntime().exec(CMD);

            // Get input streams
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            // Read command standard output
            String s;
            System.out.println("Standard output: ");
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);

            }

            // Read command errors
            System.out.println("Standard error: ");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
}


public test() {
    String FINDIP = "netsh interface ip show config name=\"Local Area Connection\" | Find \"IP\"";
    //System.out.println(FINDIP);
    executecommand(FINDIP);

}


public static void main(String[] args) {
    new test();
}
}

觉得你们也许能帮上忙。

【问题讨论】:

  • 你需要执行一个shell来构建管道,也就是sh -c "ls | wc"cmd /c "dir | find \"T\""
  • 我该怎么做呢?我只是 java 的新手,还在学习中。
  • 别担心,我刚刚解决了!非常感谢,谢谢!
  • @KaneCharles - 你应该发布你自己的答案然后选择它! :)
  • 解决方案是什么?

标签: java windows command cmd pipe


【解决方案1】:

幸运的是,有一种方法可以运行包含 管道 的命令。该命令必须以cmd /C 为前缀。例如:

public static void main(String[] args) throws Exception {
    String command = "cmd /C netstat -ano | find \"3306\"";
    Process process = Runtime.getRuntime().exec(command);
    process.waitFor();
    if (process.exitValue() == 0) {
        Scanner sc = new Scanner(process.getInputStream(), "IBM850");
        sc.useDelimiter("\\A");
        if (sc.hasNext()) {
            System.out.print(sc.next());
        }
        sc.close();
    } else {
        Scanner sc = new Scanner(process.getErrorStream(), "IBM850");
        sc.useDelimiter("\\A");
        if (sc.hasNext()) {
            System.err.print(sc.next());
        }
        sc.close();
    }
    process.destroy();
}

注意事项

【讨论】:

  • cmd /C 运行良好,谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-03-21
  • 1970-01-01
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多