Search code examples
javajarconsoleterminaljava.util.scanner

How to build your non-gui Java program into a console program


I dont know how to describe it well, but i will try. Ok, i want to be able to build my java program so that when it opens, it will look and work exactly as it does in the console. So it reads the Scanner class and prints normally, and does everything it would do if it was in the console. Ive looked around for this and havent found anything. I can make a gui java program fairly easily, but i would rather have a terminal, console like program, that works exactly as the java console, thanks.


Solution

  • You might be looking for the standard input and output members of the java.lang.System class:

    class HelloWorld {
    
      public static void main(String... argv) {
        System.out.println("Hello, World!");
      }
    
    }
    

    For processing input, you can use Scanner on standard input:

    Scanner scanner = new Scanner(System.in);
    

    If you want to get really fancy, you can print some of your output to System.err, which is a PrintStream just like System.out.


    From the comment, "when i compile my classes i get a jar file, which does nothing when i click on it, which i think is normal because its not gui," I think your problem is an operating system problem (Windows?), not a Java problem.

    Windows maps the "Open" action for JAR files to run with javaw.exe, which doesn't create a console. You'll either need to modify the default file association on each machine, or create something like a batch file that overrides this default behavior.

    You could write two programs: the first is your actual "console" Java application, and another is just a shell that uses Runtime.exec() to create a Windows console (cmd) and executes the first program within it.

    There are also opensource projects (check Sourceforge) that wrap your JAR in a Windows executable.