tags:

views:

337

answers:

4

I wrote a little commandline-application in Java and wanted to use the new class java.io.Console for this. I use System.console() to get an instance of this class. This call returns a working console, if I call my application via 'java -jar MyApp.jar' but is unset if I execute the application via the java-task of ant. fork is true and spwan false for this call. Why is this difference (System.out.print() works fine under ant)? How can I use a Console also if I start my App via ant?

+7  A: 

The Javadoc for this method states:

Returns the unique Console object associated with the current Java virtual machine, if any.

And the docs for the System.Console class state:

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.

I would imagine that when Ant forks a new Java process it redirects standard output.

matt b
So in which cases would `System.Console` actually be useful? I can't expect that the user will never redirect streams.
Bastien Léonard
Cases in which you want a fine-grained ability to read/write to the console, perhaps if you are doing some type of curses-like behavior. I would think you would want your app to check if it is null and branch to a different type of behavior if output is redirected.
matt b
btw, what I was referring to when saying "curses-like behavior": http://en.wikipedia.org/wiki/Curses_(programming_library) and http://en.wikipedia.org/wiki/Ncurses
matt b
+2  A: 

System.console() returns null if input or output is redirected. Ant just does that.

fg
+1  A: 

Well, ant is a build automation tool. Usually interactive applications have little to no place within build automation, so it's not entirely unexpected that you won't get a console when running tasks through ant.

Joey
A: 

It looks like the ant java task is using javaw.exe instead of java.exe. javaw doesn't have a console attached to it.

Cooper