Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to know if a Java program was started from the command line or from a jar file?

I want to either display a message in the console or a pop up, so in case a parameter is not specified, I want to know to which should I display

Something like:

if( !file.exists() ) {     if( fromCommandLine()){         System.out.println("File doesn't exists");     }else if ( fromDoubleClickOnJar() ) {         JOptionPane.showMessage(null, "File doesn't exists");     }  } 
like image 647
OscarRyz Avatar asked May 20 '10 00:05

OscarRyz


People also ask

Can you run a Java program from command line?

Type 'javac MyFirstJavaProgram. java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type ' java MyFirstJavaProgram ' to run your program.

How can you identify the process in Java?

You can use the jps utility that is included in the JDK to find the process id of a Java process. The output will show you the name of the executable JAR file or the name of the main class. jps tool is now included in JDK/bin directory.


1 Answers

The straight forward answer is that you cannot tell how the JVM was launched.

But for the example use-case in your question, you don't really need to know how the JVM was launched. What you really need to know is whether the user will see a message written to the console. And the way to do that would be something like this:

if (!file.exists()) {     Console console = System.console();     if (console != null) {         console.format("File doesn't exists%n");     } else if (!GraphicsEnvironment.isHeadless()) {         JOptionPane.showMessage(null, "File doesn't exists");     } else {         // Put it in the log     }  } 

The javadoc for Console, while not water tight, strongly hints that a Console object (if it exists) writes to a console and cannot be redirected.

Thanks @Stephen Denne for the !GraphicsEnvironment.isHeadless() tip.

like image 97
Stephen C Avatar answered Oct 05 '22 22:10

Stephen C