Question

public static void main(String args[]) {
    try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("mvn -version");
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isrerr = new InputStreamReader(stderr);
            BufferedReader brerr = new BufferedReader(isrerr);
            InputStream stdin = proc.getInputStream();
            InputStreamReader isrin = new InputStreamReader(stdin);
            BufferedReader brin = new BufferedReader(isrin);
            String line = null;
            while ((line = brerr.readLine()) != null)
               System.out.println(line);
            while ((line = brin.readLine()) != null)
               System.out.println(line);
            int exitVal = proc.waitFor();
       } catch (Throwable t) {
            t.printStackTrace();
       }
}

this code doesn't work well,there isn't output,and the process can't stop.

help me!thank advance.I want to execute maven command in java program by invoking command line,but it output error:it will output error java.io.IOException: Cannot run program "mvn": but if i run the same command int the command line , it works well.

Était-ce utile?

La solution

You should get the process output with proc.getInputStream()

Unless you know your program is always returning trivial amounts of output, it's best to read both the error stream and the input stream in separate threads.

Then use proc.waitFor() and get your output from the reader threads.

Otherwise, your process may block, because it cannot deliver it's output.

Sample code: import java.io.*;

public class Test {

    static class StreamReader extends Thread {
        InputStream stream;
        StreamReader(InputStream stream) {
            this.stream = stream;
        }

        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader(stream);
                BufferedReader br = new BufferedReader(isr);
                String line = null;
                while ((line = br.readLine()) != null)
                    System.out.println(line);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }

    public static void main(String args[]) {
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("mvn -version");
            new StreamReader(proc.getInputStream()).start();
            new StreamReader(proc.getErrorStream()).start();
            int exitVal = proc.waitFor();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top