1

I have a GUI program that is executed by default via javaw.exe using a startup wrapper created with Launch4j.

This program can also be executed from command-line and then print output to the console.

How can I detect if a console is visible, hence that the text I output via System.out.println() is visible?

From my understanding this depends on whether the program has been started via Javaw/wrapper or directly by java -jar myprog.jar. Is there a way to distinguish both starts methods from withing the program?

Robert
  • 36,354
  • 15
  • 89
  • 140

2 Answers2

3

If System.console() returns null, there's no console, which happens when you start the program with javaw instead of java. Example:

import javax.swing.JOptionPane;

public class Example {
    public static void main(String[] args) {
        if (System.console() != null) {
            System.out.println("Hello on the console");
        } else {
            JOptionPane.showMessageDialog(null, "Hello, there's no console");
        }
    }
}

Try compiling this and then starting it with either java Example or javaw Example.

Jesper
  • 195,030
  • 44
  • 313
  • 345
-1

$0 is the program that started the last cmd -- in the shell.

awm
  • 2,625
  • 2
  • 17
  • 26