Tutorial :Creating a console in Java



Question:

When I try to use java.lang.System.console(), I get a null pointer. I can still write to out and read from in, but this only works when I run straight from my IDE. When I run the .jar file directly, nothing happens. How can I create a console like I'd see using std::cout for use in Java?

Edit: I was hoping to just create one, rather than understand why I don't have one, since I need one for my program's operation.


Solution:1

Perhaps you're trying to get the console by double-clicking in the jar

Try creating a batch file that opens the console for you.

You can however create a console using Swing and redirect standard input/output there.

Source: Create Java console inside a GUI panel


Solution:2

How are you running the JAR file exactly? That would be the expected behavior for double-clicking its icon in Windows Explorer, as Kelly alluded to, but not for firing it up from the command line.

From the Console entry in the API (emphasis mine):

Whether a virtual machine has a console is dependent upon the underlying platform and also upon the manner in which the virtual machine is invoked. If the virtual machine is started from an interactive command line without redirecting the standard input and output streams then its console will exist and will typically be connected to the keyboard and display from which the virtual machine was launched. If the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console.


Solution:3

java.lang.System.out and java.lang.System.in are the input/output streams for console access. Java won't create a "console" but allows you to interact with the IO streams provided by the operating system.

When you run it from a jar file (like clicking on it from a folder) you'll get the I/O streams of the GUI which don't display anywhere.

Try creating a batch file with a 'java -jar ' command in it. When you run the batch file, you should see the command window. I'm assuming windows here. Another way is to run cmd.exe directly with arguments that keep the window open, i.e. "cmd.exe /c".


Solution:4

Instead of running the jar file directly, open a console (you didn't specify an operating system, but this would be the command line on Windows and a console on *Nix, or Terminal on OS X). Then, run java -jar /path/to/your.jar.

The equivalent of std::cout in Java would be System.out as you probably already know.

EDIT: With regards to your edit, there is code out there to do this. For example, you can use Swing. There's even a StackOverflow answer with more than one working code sample.


Solution:5

See JConsole, which is a general console in java, used for instance by groovy. Or see groovy directly.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »