Using CMD as a Process

后端 未结 6 1634
無奈伤痛
無奈伤痛 2020-12-22 09:38

I\'m trying to run commands straight through the CMD on Windows (Terminal on Linux). I have the following code. It\'s acting very strangely. First, when run the program does

6条回答
  •  生来不讨喜
    2020-12-22 10:12

    There could be a couple of things going on. One is that arguments are not getting passed correctly the way you are executing the process. The other, like @zacheusz mentioned, is that output may be coming out from the error stream instead of the input stream.

    ProcessBuilder helps with both these things, allowing easy construction of a list of commands and the ability to merge input and error stream. I recommend trying using it:

    Process p = null;
    try {
        List cmd = new LinkedList();
        cmd.add("executable");
        cmd.add("-arg1");
        cmd.add("value1");
        cmd.add("-arg2");
        ProcessBuilder pb = new ProcessBuilder(cmd);
        pb.redirectErrorStream(true);
        p = pb.start();
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while (input.ready()) {
            String line = input.readLine();
            System.out.println("From process: "+line);
        }
        input.close();
    } catch (IOException e) {
        this.logMessage("IOException caught: "+e.getMessage());
        e.printStackTrace();
    }
    

提交回复
热议问题