Java - How to enter runtime arguments (of main method) by double-clicking a jar file?
I encountered this problem several times. If I pack a Java application in an executable jar file that takes arguments from a user, then the user have to invoke the program (jar file) from the command prompt by the following command:
java -jar "ja开发者_StackOverflow社区r-file-name.jar"
But I want that whenever a user double clicks on the executable jar file (that needs arguments from the user), a window (command-prompt window) appears that would appear if we had invoked the jar file from the command-prompt.
I know one solution to this is using batch file .bat
to run the jar file. Is there any other solution?
To explain why:
There are 2 java JVM exe launchers:
- java.exe: console based - provides console input/output.
- javaw.exe: for GUI apps - hides the console.
JAR file extensions are associated with javaw.exe by default, which is why you don't get a console when you double-click them.
The answers others have given, and adding my own:
rewrite your app so that it uses Java GUI items for input and output instead of System.in/System.out. This may be over-complex for what you require.
You mentioned creating a batch file so that the console-based Java JVM (java.exe) is run, You could also create a windows shortcut specifying the command line:
java -jar jar-file-name.jar
You could change the windows file associations for .jar (but generally this is a bad idea -- new Java installs may reset this, and it will mean all java apps run from jars will have a console)
You could use a Java launcher like WinRun4J which allows you to simply drop a double-clickable EXE with an icon and a config file that specifies how your app should be run (with/without console, and with any other JVM and command line parameters )
Personally I went for the last option in my project - I made my jar file non-executable, and the user has to double-click the EXE. It also allowed me to specify a nice icon for my project, and provide multiple options on launch (debug/non-debug mode) simply by having a different exe/config file.
You would need to reassign the explorer association for ".jar" to java.exe instead of javaw.exe. This is somewhat of a questionable thing to do - it might make more sense to create your console output window. You can, of course, trivially pop up a dialog for user input of required execution parameters if they are not supplied on the command line.
There is working code for a console output JTextArea here.
This is an operating system feature.
If you want full control, then you must provide this functionality inside your program (or with a wrapper class.
精彩评论