- Как создать и выполнить файл .Jar в терминале Linux
- Как создать JAR-файл в Linux
- Как запустить jar в Linux
- Как запустить jar Linux
- Выводы
- How to Create and Execute a .Jar File in Linux Terminal
- How to Create a JAR File in Linux
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Creating and Executing a .jar File in Linux Terminal
- Requirements
- Create Jar files
- How to Run Jar File in Ubuntu Linux
- How to execute Jar file in Ubuntu and other distributions
- Further troubleshooting Jar file not running on Linux
Как создать и выполнить файл .Jar в терминале Linux
JAR (Java ARchive) – это независимый от платформы формат файла, используемый для объединения многих файлов классов Java и связанных с ними метаданных и ресурсов, таких как текст, изображения и т. д., в один файл для распространения.
Он позволяет Java-средам эффективно разворачивать целое приложение в одном архиве и предоставляет множество преимуществ, таких как безопасность, его элементы могут быть сжаты, сокращено время загрузки, позволяетcz уплотнение пакетов и управление версиями, поддерживает переносимость.
Он также поддерживает упаковку для расширений.
В этой статье мы покажем, как создать простое приложение Java и связать его с JAR-файлом и продемонстрируем, как выполнить файл .jar из терминала Linux.
Для этого у вас должен быть установлен инструмент командной строки java для запуска приложения Java и флаг -jar для выполнения программы, инкапсулированной в файл JAR.
Когда этот флаг используется, указанный JAR-файл является источником всех пользовательских классов, а другие параметры пути класса игнорируются.
Как создать JAR-файл в Linux
1. Сначала начните с написания простого Java-класса с основным методом для приложения TecmintApp для демонстрационных целей.
Скопируйте и вставьте следующий код в файл TecmintApp.java.
Сохраните файл и закройте.
2. Затем нам нужно скомпилировать и упаковать класс в JAR-файл, используя утилиты javac и jar, как показано ниже:
3. Создана Ounce tecmint app.jar, теперь вы можете выполнить файл с помощью команды java, как показано ниже:
Из вывода приведенной выше команды видно, что мы столкнулись с ошибкой. JVM (Java Virtual Machine) не смог найти наш основной атрибут, поэтому он не смог найти основной класс, содержащий основной метод (public static void main (String [] args)).
Файл JAR должен иметь манифест, содержащий строку в форме Main-Class: classname, которая определяет класс с основным методом, который служит отправной точкой нашего приложения.
4. Чтобы исправить вышеуказанную ошибку, нам нужно будет обновить JAR-файл, чтобы включить атрибут манифеста вместе с нашим кодом.
Давайте создадим файл MANIFEST.MF.
Скопируйте и вставьте следующую строку в файл MANIFEST.MF.
Сохраните файл и добавьте файл MANIFEST.MF в наш tecmintapp.jar, используя следующую команду:
5. Наконец, когда мы снова выполним файл JAR, он должен предоставить нам ожидаемый результат, как показано на выводе:
Для получения дополнительной информации см. Man-страницы java, javac и jar.
Источник
Как запустить jar в Linux
Java — это кроссплатформенный язык программирования, благодаря которому программы, написанные один раз, можно запускать в большинстве операционных систем: в Windows, Linux и даже MacOS. И всё это без каких-либо изменений.
Но программы, написанные на Java, распространяются в собственном формате .jar, и для их запуска необходимо специальное ПО — Java-машина. В этой небольшой статье мы рассмотрим, как запустить jar-файл в Linux.
Как запустить jar Linux
Как я уже сказал, для запуска jar-файлов нам необходимо, чтобы на компьютере была установлена Java-машина. Если вы не собираетесь ничего разрабатывать, вам будет достаточно Java Runtime Environment или JRE. Что касается версии, то, обычно, большинство программ работают с 7 или 8 версией. Если нужна только восьмая, то разработчики прямо об этом сообщают. Посмотреть версию Java и заодно убедиться, что она установлена в вашей системе, можно с помощью команды:
У меня установлена восьмая версия, с пакетом обновлений 171. Если вы получаете ошибку, что команда не найдена, то это значит, что вам нужно установить java. В Ubuntu OpenJDK JRE можно установить командой:
sudo apt install openjdk-8-jre
Если вы хотите скомпилировать пример из этой статьи, то вам понадобиться не JRE, а JDK, её можно установить командой:
sudo apt install openjdk-8-jdk-headless
Чтобы узнать, как установить Java в других дистрибутивах, смотрите статью по ссылке выше. Когда Java будет установлена, вы можете очень просто запустить любой jar-файл в Linux, передав путь к нему в качестве параметра Java-машине. Давайте для примера создадим небольшое приложение:
public class Main <
public static void main(String[] args) <
System.out.println(» Losst test app! «);
>
>
Затем скомпилируем наше приложение в jar-файл:
javac -d . Main.java
jar cvmf MANIFEST.MF main.jar Main.class
Теперь можно запустить наш jar-файл командой java с параметром -jar:
java -jar main.jar
Таким образом вы можете запустить любой jar-файл, который собран для вашей версии Java. Но не очень удобно каждый раз открывать терминал и прописывать какую-либо команду. Хотелось бы запускать программу по щелчку мышки или как любую другую Linux-программу — по имени файла.
Если мы дадим программе право на выполнение:
chmod u+x ./main.jar
И попытаемся её запустить, то получим ошибку:
Чтобы её исправить, нам понадобиться пакет jarwrapper:
sudo apt install jarwrapper
Теперь можно запускать java в Linux по щелчку мыши или просто командой.
Выводы
В этой небольшой статье мы рассмотрели, как запустить jar Linux с помощью java-машины, а также как упростить команду запуска. Если у вас остались вопросы, спрашивайте в комментариях!
Источник
How to Create and Execute a .Jar File in Linux Terminal
A JAR (Java ARchive) is platform-independent file format used to aggregate many Java class files and associated metadata and resources such as text, images, etc, into a single file for distribution.
It allows Java runtimes to efficiently deploy an entire application in one archive file, and provides many benefits such as security, its elements may be compressed, shortening download times, allows for package sealing and versioning, supports portability. It also supports packaging for extensions.
In this article, we will show how to create a simple Java application and bundle it into a JAR file, and demonstrate how to execute a .jar file from the Linux terminal.
To do this, you must have java command line tool installed to launche a Java application, and the -jar flag to execute a program encapsulated in a JAR file. When this flag is used, the specified JAR file is the source of all user classes, and other class path settings are ignored.
How to Create a JAR File in Linux
1. First start by writing a simple Java class with a main method for an application called TecmintApp, for demonstration purpose.
Copy and paste the following code to TecmintApp.java file.
Save the file and close it.
2. Next, we need to compile and pack the class into a JAR file using the javac and jar utilities as shown.
3. Once tecmintapp.jar created, now you can excute the file using java command as shown.
From the output of the above command, we encountered an error. The JVM (Java Virtual Machine) couldn’t find our main manifest attribute, thus it could not locate the main class containing the main method (public static void main (String[] args)).
The JAR file should have a manifest that contains a line in the form Main-Class:classname that defines the class with the main method that serves as our application’s starting point.
4. To fix the above error, we will need to update the JAR file to include a manifest attribute together with our code. Let’s create a MANIFEST.MF file.
Copy and paste the following line to MANIFEST.MF file.
Save the file and let’s add the file MANIFEST.MF to our tecmintapp.jar using following command.
5. Finally, when we executed the JAR file again, it should produce the expected result as shown in the output.
For more information, see the java, javac and jar command man pages.
That’s all! In this short article, we have explained how to create a simple Java application and bundle it into a JAR file, and demonstrated how to execute a .jar file from the terminal. If you have any questions or supplementary ideas to share, use the feedback form below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Creating and Executing a .jar File in Linux Terminal
JAR – Java Archive. It is like a zip file but for java classes. It combines all the .class files in Java into a single .jar file. It is used to download all java classes on HTTP in a single operation. These can be created using the “jar” CLI tool. It also has an optional META-INF which can include files like –
- MANIFEST.MF – manifest file is used to define the extension and package-related data.
- INDEX.LIST – It contains location information for packages defined in an application or extension.
- x.SF – This is the signature file where ‘x’ is the base file name.
- x.DSA – This file stores the digital signature of the corresponding signature file.
- services/ – This directory stores all the service provider configuration files.
The most common and majorly used file is MANIFEST.MF
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Requirements
Java (JDK + JRE) must be installed. Check by using command –
Create Jar files
Let us consider 4 class files – Class1, Class2, Class3, Class4
Источник
How to Run Jar File in Ubuntu Linux
Last updated October 29, 2019 By Abhishek Prakash 19 Comments
Got a Jar file but struggling to execute it? Learn how to run a Jar file in Ubuntu and other Linux distributions.
How to execute Jar file in Ubuntu and other distributions
A Jar file is basically a Java executable file. So you must have Java installed on your system. If you have Java installed in your Ubuntu, you should be able to run it either by double clicking or by selecting from right click options.
The problem here is that most Linux distributions don’t come with Java pre-installed. So please make sure to install Java on Ubuntu. or whichever distribution you are using.
You only need the Java Runtime Environment and you can install it using the command below in Ubuntu-based distributions:
Even with Java installed, sometimes running a Java application is not as straightforward as double-clicking the icon. You might have to go through a few steps.
When I tried to open the .jar file by double clicking, I was presented with the following error:
Fixing this error is very trivial. Right click the .jar file, and open properties.
Now in the properties menu, open the ‘Permissions’ tab. Enable the ‘Allow executing this file as program’ checkbox.
Now, you can simply double click the .jar file to launch the application, AndroMouse in my case. You can see that it works without any problems.
You have to keep in mind that you have to enable the ‘Allow executing as program’ permission for every .jar application you download. It is disabled by default as a security measure. You should enable it only for the applications that you trust and know are safe.
Further troubleshooting Jar file not running on Linux
Even if you have Java Runtime Environment installed and execution permission set, in some older versions of Ubuntu, the Jar file won’t run. Here’s a fix for that.
Right click on the .jar file and choose the option “Open With Other Application“:
Now on the next screen, select the option Show other applications:
In other applications, if you do not find option for Java, install the Java Runtime Environment first. Normally, you should be able to see the option Open With OpenJDK Java x Runtime. Select it and successfully run it.
Enjoy running Jar file on Ubuntu!
I hope this short guide was useful to all of you. Which Java based applications do you use? Do you have any other problems with them? Let me know in the comments below!
Like what you read? Please share it with others.
Источник