Search code examples
javasyntaxprocessbuilder

Java ProcessBuilder Syntax for Initial construction with Command


I am trying to run a command which I give my ProcesBuilder as parameter while constructing.

The command is the following:

wmic process where name='OUTLOOK.EXE' get CommandLine

I normally just would run it with a pb.command() but I need to "catch" the output which I already did via a BufferedReader.

So my question is how I can do the Syntax right if I want to do something like:

ProcessBuilder pb = new ProcessBuilder("wmic process where name='OUTLOOK.EXE' get CommandLine");

I know I have to split this up somehow but I can't figure out how.

full method looks like :

    public static void sendmail() throws IOException {

        ProcessBuilder pb = new ProcessBuilder("wmic process where name='OUTLOOK.EXE' get CommandLine");
        final Process p=pb.start();

        BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        StringBuilder sb = new StringBuilder();
        while((line=br.readLine())!=null) sb.append(line);


        System.out.println(sb.toString());

}

Solution

  • Separate the command argument should work.

    import java.io.IOException;
    
    public class WmicProcessRunner {
        public static void main(String[] args) {
            try {
                ProcessBuilder processBuilder = new ProcessBuilder("wmic", "process", "where", "name='OUTLOOK.EXE'", "get",
                        "CommandLine");
                processBuilder.inheritIO();
                Process wmicProcess = processBuilder.start();
                while (wmicProcess.isAlive()) {
                    Thread.sleep(1000);
                }
                wmicProcess.destroy();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }