简体   繁体   中英

Command prompt is not closing after completing even after writing exit

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.

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM