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

在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);
        }
    }
}
mre asked 2020-08-12T08:30:26Z
5个解决方案
36 votes
Runtime.getRuntime().exec("netsh");

请参阅运行时Javadoc。

编辑:后来由leet给出的答案表明此过程现已弃用。 但是,根据DJViking的评论,情况似乎并非如此:Java 8文档。 该方法未弃用。

badroit answered 2020-08-12T08:30:36Z
28 votes

使用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.
}
leet answered 2020-08-12T08:30:55Z
5 votes

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

Marko Zajc answered 2020-08-12T08:31:40Z
2 votes

Runtime#exec().

Matt Ball answered 2020-08-12T08:32:02Z
2 votes
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();
    }
}

这可行。

Anubis05 answered 2020-08-12T08:32:55Z
translate from https://stackoverflow.com:/questions/7112259/how-to-execute-windows-commands-using-java-change-network-settings