views:

1480

answers:

3

I have this class:

public class Test {
 public static void main(String[] args) {
  System.out.println("Hello World!");
 }
}

And I used Eclipse's "Export to runnable JAR" function to make it into a executable jar-file (test.jar). When I run this program in Eclipse, it prints out "Hello World!", but when I call the jar-file from the command line, nothing happens.

I have tried calling the jar-file like this:

test.jar
test.jar -jar

There is no output whatsoever.

I have another program that also has a side effect (in addition to output to stdout) and while the side effect is being performed (which tells me the jar-file was definitely executed), again no output is given to the command line. I have also tried using stderr, but that makes no difference. Does anybody know how I can make this work?

Thanks!

+6  A: 

You must run the JAR using

java -jar test.jar

(Your JRE's bin folder must be added to PATH in order to get the command working from any location)

NOTE: I know you created the JAR using Eclipse but you might want to know how does an executable JAR works

victor hugo
I believe this answer is correct. Executing just "test.jar" will probably be using "javaw.exe" which is the console-less version of "java.exe" that by default is associated with .jar files.
pauldoo
Yes... only on Windows
victor hugo
The JRE installs itself in the PATH on Windows pr default, so "java.exe" should be available immediately thereafter.
Thorbjørn Ravn Andersen
+3  A: 

When you invoke the jar using 'test.jar' the starting of the app is handed off to the registered java handler for jar files, which doesn't run in the context of the command line.
The default jar handler doesn't open console based System.{out,err} file handles, as it would mean a cmd style window for each of the jar files launched, which is not an ideal situation.
The previous answer, using java -jar test.jar causes it to run within the context of the current cmd window, and thus you will see the output.

Petesh
+4  A: 

The previous answers are correct, so I'll just clarify a bit the "executable jar" concept. There's no such thing as an "executable jar", equivalent to an exe file in windows, in an "executable jar" you'll be only specifying the "entry" point ( your main class you want to be executed by default )

A jar is basically just an archive, you'll still need java to actually launch the jar ( java -jar your.jar )

The fact that in windows you might have an association with javaw.exe means this will be launched by the OS when you double-click on the jar, like a .txt file being opened automatically with notepad, it doesn't make the .txt an executable file.

Check this out as well : JAR files revealed

Billy