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

时间:2011-08-18 18:26:50

标签: java windows runtime.exec

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

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

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

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


以下是我实施的未来参考解决方案:

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

5 个答案:

答案 0 :(得分:34)

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

Runtime Javadoc。

编辑:leet稍后的回答表明此流程现已弃用。但是,根据DJViking的评论,情况似乎并非如此:Java 8 documentation。该方法不推荐使用。

答案 1 :(得分:27)

使用ProcessBuilder

ProcessBuilder pb=new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process process=pb.start();
BufferedReader inStreamReader = new BufferedReader(
    new InputStreamReader(process.getInputStream())); 

while(inStreamReader.readLine() != null){
    //do something with commandline output.
}

答案 2 :(得分:5)

您可以使用Runtime.getRuntime().exec("<command>")运行命令(例如Runtime.getRuntime().exec("tree"))。但是,这只会运行在路径中找到的可执行文件,而不是echodel等命令,但只有tree.comnetstat.com之类的内容,...运行常规命令,您必须在命令之前放置cmd /c(例如Runtime.getRuntime().exec("cmd /c echo echo")

答案 3 :(得分:2)

答案 4 :(得分:2)

public static void main(String[] args) {
    String command="netstat";
    try {
        Process process = Runtime.getRuntime().exec(command);
        System.out.println("the output stream is "+process.getOutputStream());
        BufferedReader reader=new BufferedReader( new InputStreamReader(process.getInputStream()));
        String s; 
        while ((s = reader.readLine()) != null){
            System.out.println("The inout stream is " + s);
        }                   
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这很有效。