简体   繁体   中英

System.out.println in jar

I have this java program that I want to package within a jar. It compiles fine and it compiles without errors into a jar. But when I double click it, it wont start. I know most jar applications uses JFrame and that works fine. But is it possible to make it command prompt/shell based? (Like Displaying System.out.println)

Example is it possible to execute this code by double clicking a jar:

public class Hello
{

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

There is no problem doing like that. But where do you expect to see the output?

If you execute from the console as java -jar my jar.jar you will see your "Hello, World".

If you want to double-click you'll need to create a JFrame.

You can change the file association for jar files to have them open a console. (This is for Windows)

  • Open Command Processor
  • Type ftype jarfile
  • You will get something like:

jarfile="C:\\Path\\To\\Java\\bin\\javaw.exe" -jar "%1 %*"

  • Enter ftype jarfile "C:\\Path\\To\\Java\\bin\\java.exe" -jar "%1" %* (You may need administrator privileges to do this).

I don't see anyone mentioning the obvious solution: make a .cmd (or .bat) file containing the command everyone is talking about -- java -jar YourJar.jar . You can double-click on the .cmd file and a console window will open. It will also close imediately as your program exits, so the program should wait for a keypress before exiting.

Sure. First try to run your program as following:

java -cp yourjar.jar Main

where Main is a fully qualified class name of your main class.

When this is working fine and if you creted exacutable jar try to run your program as following:

java -jar yourjar.jar

When this is working double click should work too unless you mapped extension jar to program other than javaw that is done by default when you are installing JRE.

If you want to display the "Hello, world!" String you have to execute your code from the command line:

   jar -jar your_jar_name.jar

The output gets forwarded to the console but without eclipse, there isn't any! The only way to work around this is to launch the program in command prompt and then you will get the output from the program.

You can make a jar an executable by including a manifest file which contains the name of the class that has your main method (in your example that would be Hello). Here is a link that details what you need to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM