javacmdconsoleprocessbuilderattachedbehaviors

Java how to start CMD and stay attached to it for user interaction?


I'm struggling with the following issue: I am trying to build an application that, when run, opens a CMD window (visible to the user) and that is attached to that window's input and output (so that it functions like the console of the application). So if the user types something in the CMD window, then for example a Scanner(System.in) can pick it up, and when I do System.out.println then it appears in the CMD window.

I know that one could simply run the .jar file from CMD and attach it like that, but that's not what I want. I want the .jar to open a CMD window on itself and use that as it's console (visible to the user).

Looking forward to some suggestions :)


Solution

  • With thanks to Poohl's suggestion, I came up with the following solution:

    When the .jar is launched without arguments, it automatically looks for a .bat file "launcher.bat" in the same folder and launches that file through a CMD process:

        if(args.length > 0 && args[0].equals("ATTACH") {
            // Execute command-line program....
        } else {
            ArrayList<String> commands = new ArrayList<>();
            commands.add("cmd.exe");
            commands.add("/c");
            commands.add("start");
            commands.add("cd " + new File("").getAbsolutePath()); // cd to classpath
            commands.add("launcher.bat"); // The launcher that is in classpath
    
            ProcessBuilder pb = new ProcessBuilder(commands);
    
            Process p = pb.start();
        }
    

    The .bat file contains the following statement:

    java -jar LineCounter.jar ATTACH
    

    As a result, the cmd window which was opened with the processbuilder will in turn again open the bat file which opens the .jar file and remains attached to it.