java - 如何使用 Java 执行 Windows 命令 - 更改网络设置

标签 java windows runtime.exec

在 Java 中,我希望能够执行 Windows 命令。

有问题的命令是 netsh。这将使我能够设置/重置我的 IP 地址。

请注意,我不想执行批处理文件。

我想直接执行这样的命令,而不是使用批处理文件。这可能吗?


这是我实现的 future 引用解决方案:

public class JavaRunCommand {
    private static final String CMD = 
        "netsh int ip set address name = \"Local Area Connection\" source = static addr = 192.168.222.3 mask = 255.255.255.0";
    public static void main(String args[]) {

        try {
            // Run "netsh" Windows 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);
        }
    }
}

最佳答案

Runtime.getRuntime().exec("netsh");

Runtime Javadoc。

编辑:leet 后来的回答表明这个过程现在已被弃用。但是,根据 DJViking 的评论,情况似乎并非如此:Java 8 documentation .该方法未被弃用。

关于java - 如何使用 Java 执行 Windows 命令 - 更改网络设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7112259/

相关文章:

java - index.html 不呈现 servlet 3.0 Tomcat 7

java 扫描器忽略 ^ Caret

java - XMPP编程使用erlang还是java?

c - 在c中实现fork()

java - 无论底层操作系统如何,都从 Java 执行进程

java - 向 WinSCP 发送命令

java - 错误: Could not find or load main class - . jar文件执行

c - 按下 Winapi 按钮

java - 在某些 Windows 服务或程序启动时触发 Java 程序

java - 带有java的linux ulimit不能正常工作