-2

I have following java code

public static void main(String a[]) {
        String location = "C:\\Users\\test\\output\\testProject";
        File dir = new File("C:\\Users\\test\\cmds");
        ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "Start /wait","packageProject.bat",location);
        pb.directory(dir);
        Process p = null;
        try {
            p = pb.start();
            p.waitFor();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        catch(InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Folder created");
    }

Batch file is

cd "C:\Users\test\output\test-master"

mvn clean install -DskipTests

exit

It is packaging file but not command prompt is not closing once process is complete.

Please suggest.

  • A console session won't end automatically as long as it has client processes or as long as a process has a handle to its input buffer or one of its screen buffers. This could happen if `mvn` starts processes that attach to the console and are still running after mvn.exe exits. – Eryk Sun Jul 23 '20 at 14:11

1 Answers1

0

You should remove wrapper CMD.EXE and start, just call the batch file directly as:

String bat = new File(dir, "packageProject.bat").getAbsolutePath();
ProcessBuilder pb = new ProcessBuilder(bat , location);
pb.directory(dir);
Process p = pb.start();
p.waitFor();

If this process generates a lot of output you may run into a second problem if you don't consume error and output streams. You can do this in background threads, or simply send stdout/err to files by adding these calls before pb.start():

pb.redirectOutput(new File(location, "std.out"));
pb.redirectError(new File(location, "std.err"));
DuncG
  • 12,137
  • 2
  • 21
  • 33