How to run exec from Java for netsh?

自闭症网瘾萝莉.ら 提交于 2019-12-12 02:44:13

问题


The following works fine when i type it in directly into cmd.exe:

netsh wlan connect name="Profile Name" ssid=XXXXXX

However when i try to do this from java it does not work, neither does it throw any exception. It is silently ignored:

Runtime.getRuntime().exec("cmd netsh wlan connect name=\"Profile Name\" ssid=XXXXX ") ; ` 

How can i improve the code ?


回答1:


First try removing the cmd parameter (you don't need to run this interpreter, just netsh).

Else it may be due to whitespace characters in this command line (be careful of whitespace in SSID for example). You may want to try Runtime.exec(String[] cmdarray) or java.lang.ProcessBuilder instead to specify each parameter individually.

Examples:

Runtime.getRuntime().exec(new String[] {"netsh", "wlan", "connect", "name=\"Profile Name\"", "ssid=XXXXX"});

or (complete example):

ProcessBuilder pb = new ProcessBuilder("netsh", "wlan", "connect",
    "name=\"Profile Name\"", "ssid=XXXXX");
pb.redirectErrorStream(true);
Process process = pb.start();
BufferedReader reader = new BufferedReader(
    new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
    System.out.println(line);
}


来源:https://stackoverflow.com/questions/22998541/how-to-run-exec-from-java-for-netsh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!