Как запустить jar на linux
Перейти к содержимому

Как запустить jar на linux

  • автор:

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

Requirements

Java (JDK + JRE) must be installed. Check by using command –

Create Jar files

Let us consider 4 class files – Class1, Class2, Class3, Class4

Output

Let’s move them into one jar file called “allClasses.jar”.

Run the command:

jar –create –file allClasses.jar Class1.class Class2.class Class3.class

To get a clear output use –verbose

jar –create –verbose –file allClasses.jar Class1.class Class2.class Class3.class

Output:

This will create an allClasses.jar file in the folder. Let’s understand the above command thoroughly.

  1. –create: It is an option to create a jar file. We can perform more operations like extract, update, etc.
  2. –verbose: It gives a crisp and clear output and shows what’s going on behind the scenes.
  3. –file filename: filename is the name for the jar file. Extension(.jar) is optional.
  4. In the end, we specify the whole list of files to put in the jar file.

The shorthand for this command will be –

Note: * represents all the files in the current folder. Use * with caution.

To update,

-u is for the –update.

This will update allClasses.jar files with the new Class4.class.

From the verbose output, it is clear that compression is taking place, to bypass compression or to archive files without compression use the option –no-compress.

jar –create –verbose –no-compress –file allClasses.jar Class1.class Class2.class Class3.class

Output:

Execute Jar Files

Execution is fairly simple of jar files. Just use the command

If this gives an error – no main manifest attribute, in allClasses.jar

Open ./META-INF/MANIFEST.MF file and add a line in it.

In our case, the class name will be “Class1” as it’s our main class.

Now, the file will look like this:-

Again run the command

Output:

Caution: Don’t leave any space between lines in the MANIFEST.MF file else it will show the unexpected error.

If you still get the error and not able to find the error, use the below workaround –

Как запустить 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-машины, а также как упростить команду запуска. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

How can I execute a .jar file from the terminal

I know that to execute a file, I use the . command, then the file name with a space between them. But I’m trying to execute a .jar file using the . and it does not work. I went into the properties and marked it as executable and made it run with Java.

Is there a way to execute a file with Java in the Bash Terminal? I am trying to execute a Minecraft.jar file

I am trying to execute the Minecraft.jar file.

9 Answers 9

The . syntax can only be used to run (by «sourcing») shell scripts.

You’ll need to use the java command to run a .jar file:

If you don’t have java installed, you can fix that by installing the default-jre ¹ package. You can see if you already have java installed by running in a terminal:

[1]: This will install the default openjdk Java runtime. You can use openjdk-8-jre , or openjdk-7-jre , or openjdk-6-jre instead, if you prefer — whichever is available on your version of Ubuntu.

Linux is perfectly capable of running a foreign binary, like a JAR file. This is how Wine works, for example. To run JAR files as executable do the following in a console

Cd to your JAR file and change it to executable (you can also do this through file properties in Nautilus)

Run your jar file just as if it was any other binary executable or shell script

Note: Be sure you have binfmt_misc linux kernel module loaded. If you use your custom compiled kernel without this module, binfmt-support won’t work.

If it is an executable jar, then

Not all jar-Archives contain an executable class, declared to be started in the Manifest file, but if there is, this will work.

Btw.: You don’t start most programs from the shell with the dot. The dot is a shortcut for source , and it only works in the bash and some other shells, to include a script in the scope of the current session.

A compiled binary xybin is simply started with its name if it is in the path:

or, with its absolute path:

or with its relative path:

or if you happen to be in the directory of the file, with this relative path:

The file has to be marked executable for you (see: chmod). All of the above is true for shellscripts too, but they often have an extension .sh, and you can start a shellscript by invoking the interpreter, and then it needn’t be marked executable:

If you don’t want to start a new bash, you can use source, and you do so, to consume function definitions, aliases and variable settings.

How to run .jar file on unix?

I have generated .jar file in windows.
I have to execute that .jar file in unix .

I am running that command ( java -jar myJar.jar ), but it’s giving

I am using java version 1.5.0.12 in Unix.

VonC's user avatar

7 Answers 7

Same as under Windows.

You must be trying to launch a jar compiled with JDK6, with a local java1.5.

  • upgrade your jvm on Unix to 1.6
  • or re-compile your classes with a

to check if you can generate 1.5 bytecode compatible.

VonC's user avatar

Have you tried using a newer version of Java on your Unix system?

If you control the jar file, could you target Java 1.5 when it’s compiled?

UnsupportedVersionError means that you have compiled the Java source code with a newer version of Java than what you’re trying to run it with. Java is downwards compatible (newer versions of Java can run Java programs compiled with older versions), but not upwards compatible (older versions of Java cannot run Java programs compiled with newer versions).

You say you’re using Java 5 on Unix. Did you compile it using Java 6 on Windows? Then it’s obviously not going to work.

  • Compile your source code using Java 5 on Windows (the safest option)
  • Use the compiler flags: -source 1.5 -target 1.5 while you compile (this will not protect you against using Java 6-only classes from the standard library, so this is not a full guarantee that your program will run without errors on Java 5)
  • Upgrade to Java 6 on Unix

Recompile your application with Java 5 on your Windows machine.

(Java 6 generates Java 6 compatible byte code by default to use new facilities. The easiest for you is to install a Java 5 JDK and use it to recompile your application)

  • Check that JDK or JRE is installed. Install if it is not.
  • set JAVA_HOME= # JDK/JRE home directory
  • $JAVA_HOME/bin/java -jar file.jar

You should also keep in mind that JVM are not forward compatible, so if you’ve made a jar-file using JDK 1.6, it won’t work with JDK 1.5!

In this case you may either:

install JDK 1.6 to Unix

recompile the jar with -target 1.5 flag (but you may get any sort of errors due to API incompatibilities, so the first way is much better)

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *