Running JAR-Packaged Software
Now that you have learned how to create JAR files, how do you actually run the code you packaged? Consider these scenarios:
- Your JAR file contains an applet that is to be run inside a browser.
- Your JAR file contains an application that is to be started from the command line.
- Your JAR file contains code that you want to use as an extension.
This section will cover the first two situations. A separate trail in the tutorial on the extension mechanism covers the use of JAR files as extensions.
Applets Packaged in JAR Files
To start any applet from an HTML file for running inside a browser, you use the applet tag. For more information, see the Java Applets lesson. If the applet is bundled as a JAR file, the only thing you need to do differently is to use the archive parameter to specify the relative path to the JAR file.
As an example, use the TicTacToe demo applet. The applet tag in the HTML file that displays the applet can be marked up like this:
If the TicTacToe demo was packaged in a JAR file named TicTacToe.jar, you can modify the applet tag with the addition of an archive parameter:
The archive parameter specifies the relative path to the JAR file that contains TicTacToe.class. For this example it is assumed that the JAR file and the HTML file are in the same directory. If they are not, you must include the JAR file’s relative path in the archive parameter’s value. For example, if the JAR file was one directory below the HTML file in a directory called applets, the applet tag would look like this:
JAR Files as Applications
You can run JAR packaged applications with the Java launcher (java command). The basic command is:
The -jar flag tells the launcher that the application is packaged in the JAR file format. You can only specify one JAR file, which must contain all of the application-specific code.
Before you execute this command, make sure that the runtime environment has information about which class within the JAR file is the application’s entry point.
To indicate which class is the application’s entry point, you must add a Main-Class header to the JAR file’s manifest. The header takes the form:
The header’s value, classname, is the name of the class that is the application’s entry point.
For more information, see the Setting an Application’s Entry Point section.
When the Main-Class is set in the manifest file, you can run the application from the command line:
Запуск файла JAR в Windows
У меня есть файл JAR с именем helloworld.jar . Чтобы запустить его, я выполняю следующую команду в окне командной строки:
Это работает нормально, но как мне выполнить его двойным щелчком вместо этого? Нужно ли устанавливать какое-либо программное обеспечение?
Самый простой путь — это обновление или переустановка Java Runtime Environment (JRE).
- Откройте проводник Windows, в меню «Инструменты» выберите «Параметры папки . »
- Перейдите на вкладку «Типы файлов», прокрутите вниз и выберите «Тип файла JAR».
- Нажмите кнопку Дополнительно.
- В диалоговом окне «Редактировать тип файла» выберите «Открыть» в поле «Действия» и нажмите «Изменить».
- Нажмите кнопку Обзор и перейдите к местоположению интерпретатора Java javaw.exe.
- В Приложении, используемом для выполнения поля действия, должно отображаться что-то похожее на C:\Program Files\Java\j2re1.4.2_04\bin\javaw.exe» -jar «%1» % (Примечание: часть, начинающаяся с ‘javaw’, должна быть точно такой же; другая часть имени пути может отличаться в зависимости от используемой версии Java ) затем нажимайте кнопки ОК, пока все диалоговые окна не будут закрыты.
В Windows Vista или Windows 7 ручной редактор сопоставления файлов был удален.
Самый простой способ — запустить Jarfix , крошечный, но мощный бесплатный инструмент. Просто запустите его, и ваши Java-приложения вернутся . снова дважды щелкните мышью.
Если вам нужно распространить файл .jar и сделать его работоспособным на компьютерах Windows других людей, вы можете создать простой файл .bat, например, в командной строке:
и поместите файл .bat в тот же каталог, что и ваш файл .jar.
Если у вас есть файл jar с именем Example.jar, следуйте этим правилам:
- Открыть notepad.exe
- Напишите : java -jar Example.jar
- Сохраните это с расширением .bat
- Скопируйте его в каталог, в котором находится .jar файл
- Дважды щелкните по нему, чтобы запустить .jar файл
Интересный побочный эффект этого вызывает проблему при запуске запускаемых файлов JAR в командной строке.
Если вы попробуете (в командной строке):
Нет радости, потому что это переводится на следующее (что не работает):
Тем не менее, следующая команда работает:
Если вы измените связь в файловом менеджере, как описано выше:
Затем вы можете ввести:
в командной строке и теперь он будет работать!
РЕДАКТИРОВАТЬ: (Однако вы получите черное окно консоли при запуске Java-приложения на основе формы (не консоль), так что это не идеальное решение)
Если вы запустите эти jar-файлы, дважды щелкнув их в окнах, параметры не будут переданы, поэтому ваш Java-код должен обрабатывать исключение переполнения стека и включать в конце функцию «нажать клавишу», иначе окно просто исчезнет.
Чтобы передать параметр в windows, вы должны создать ярлык для файла JAR, который включает в себя параметр в целевой строке (щелкните правой кнопкой мыши по ярлыку и выберите свойства), вы не можете добавлять параметры к самому значку файла JAR в этом путь.
Здесь нет единого согласованного решения, но у вас будет такая же проблема с любым другим консольным приложением.
Существует бесплатное приложение для Windows под названием «bat to exe», которое можно использовать для создания exe-файла из .bat-файла с соответствующей командной строкой в нем. Вы также можете вставить jar-файл в исполняемый файл с этим приложением и заставить его очистить его после завершения работы, так что это может быть более элегантным решением.
How to Open JAR Files in Windows 7 [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
Closed 8 years ago .
I have looked this up on Google and nothing seems to suit my needs. I am using a Windows 7 computer. I have tried to re-install Java 7 and both the JRE and the JDK downloads say that I already have it on my computer.
I currently have these Java folders:
- C:\Program Files\Java\jdk1.6.0_25\
- C:\Program Files\Java\jdk1.7.0_05\
- C:\Program Files\Java\jre6\
- C:\Program Files (x86)\Java\jre7\
Which folders are obsolete and can be deleted?
How do I make it so that when I double-click on a .JAR executable file, it will properly open without me having to use a command to open it. When I try to open a JAR file currently, it opens a CMD screen and then closes right after.
3 Answers 3
Check what the .jar extension is associated with. Try running the same command from a command prompt window. Hopefully then you can see what the error is and fix it.
Uninstalling all java environments and then reinstalling just what you need will probably work. After uninstalling also delete the java*.exe files from c:\windows\system32. You should not need the JAVA_HOME environment variable to be set, but some batch files require it to be set.
If you want Java to work in your browser you must install a 32-bit JRE.
If you need to run a java program that uses a huge amount of memory (2GB+) or must call a 64 bit DLL directly using JNI or JNA then you must install a 64 bit JRE. If you do java development then you should install a a JDK instead of the JRE. Your IDE may also require that you install a 64 bit JDK instead of a 32 bit JDK.
Need help running my Java .jar file from Windows batch file
I have a Java jar file located in:
I also have some required properties files (needed as input arguments to the .jar file) located in the same directory as the .jar file.
I created a runme.bat file here:
In the runme.bat file, this is what I have:
However, whenever I try to run the .bat file, I get the error:
On the command line I see Windows trying to do this:
I get this error when running from the command line. If I simply double-click the .bat file, a cmd window comes up and quickly disappears.
So, what am I doing wrong?
1 Answer 1
Use Double quotes around the set command, not inside the variables.
Also, I see no reason to use the START command unless you want to do more in your batch file in the original command prompt after starting your Java in a second command prompt. Possible but seems unlikely.
Generally, you will just type in the executable or use CALL so that the executable runs and control returns to the batch after reaching conclusion.
Additionally, you changed your system path variable to be just the path of your java files which will make the session pretty screwy. Thankfully this should only persist in your open command windows and those spawned by the original window, so close them all and then use a different variable name for your path.
So I will put this both ways, using Call, and using start.