java getRuntime()。exec()不适用于运行基本cmd命令

时间:2017-06-15 06:50:37

标签: java cmd

我正在尝试使用getRuntime()。exec()运行cmd命令。问题是它只有在我的命令字符串 ipconfig 时才有效,而如果我尝试运行 java -version < / strong>或 时间 ,然后抛出错误:

java.io.IOException:无法运行程序“time”:CreateProcess error = 2,系统找不到指定的文件

   String command = "time";
    Process p;
    try {
         p = Runtime.getRuntime().exec(command);
         BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
         String line;
            while (true) {
                line = r.readLine();
                if (line == null) { break; }
                //System.out.println(line);
                textField_1.setText(line);
            }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

1 个答案:

答案 0 :(得分:1)

我使用ProcessBuilder解决了这个问题。我仍然不知道为什么早期的代码对所有命令都不起作用。但是,通过使用ProcessBuilder,我能够执行任何cmd查询。

以下是参考代码:

String command_ping = "ping " + host_name;

            try {

                ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", command_ping);
                builder.redirectErrorStream(true);
                Process p = builder.start();

                BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
                StringBuffer buffer = new StringBuffer();
                String line = "";
                while (true) 
                {

                    buffer.append(line).append("\n");
                    line = r.readLine();
                    if (line == null) { break; }
                }
                message_ping= buffer.toString();
                p.waitFor();
                r.close();

            } 

            catch (IOException e) 
            {
                e.printStackTrace();
            } 

            catch (InterruptedException e) 
            {
                e.printStackTrace();
            }