nmcli命令没有从java程序运行

时间:2017-09-21 17:24:15

标签: java ubuntu

我有一个使用用户字段连接到wifi网络的java程序。我正在使用nmcli连接到here

中所述的wifi网络

命令nmcli device wifi connect <SSID|BSSID> password <password>绝对可以从命令行运行。

但是我想从java程序中实现这个命令。主体如下:

        Process p;
        String command = "nmcli device wifi connect '" + wifiName + "' password " + password;
        System.out.println();
        p = Runtime.getRuntime().exec(command);
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

    String line;

    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    p.waitFor();

我不知道为什么在执行命令后控制台中没有打印任何内容。

ping等基本命令工作得很好。

修改

使用ProcessBuilder而不是Runtime.exec

Process p;
        String command = "nmcli device wifi connect '" + wifiName + "' password " + password;
        System.out.println();
        p = new ProcessBuilder(command).start();

收到错误:

Exception in thread "main" java.io.IOException: Cannot run program "nmcli device wifi connect 'wifiname' password password": error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at wificonnect.WifiConnect.main(WifiConnect.java:36)
Caused by: java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
    at java.lang.ProcessImpl.start(ProcessImpl.java:134)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 1 more
/home/oni/.cache/netbeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 10 seconds)

0 个答案:

没有答案