Открыть java на linux

Как запустить 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:

Таким образом вы можете запустить любой jar-файл, который собран для вашей версии Java. Но не очень удобно каждый раз открывать терминал и прописывать какую-либо команду. Хотелось бы запускать программу по щелчку мышки или как любую другую Linux-программу — по имени файла.

Если мы дадим программе право на выполнение:

И попытаемся её запустить, то получим ошибку:

Чтобы её исправить, нам понадобиться пакет jarwrapper:

sudo apt install jarwrapper

Теперь можно запускать java в Linux по щелчку мыши или просто командой.

Выводы

В этой небольшой статье мы рассмотрели, как запустить jar Linux с помощью java-машины, а также как упростить команду запуска. Если у вас остались вопросы, спрашивайте в комментариях!

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

Источник

How to Run Jar File in Ubuntu Linux

Downloaded a JAR file and don’t know how to use it? Learn how to run JAR files in Ubuntu based Linux distributions.

jar file not marked as executable

If you install any package having the .jar extension and try to execute it, it may throw an error saying «The file is not marked as executable»: And in this tutorial, I will walk you through how you can install its prerequisites and run Jar files in Ubuntu and other Linux with multiple methods.

Читайте также:  Acronis backup для linux

Run jar files in Ubuntu

If you don’t know, JAR stands for Java ARchive so you must have a working Java environment. If you have Java installed, you should be able to run it. Check if Java is installed with:

If you see an error instead of the version number, install Java runtime environment using the following command:

sudo apt install default-jre

So let’s start with the first one.

Method 1: Using GUI

The first step is to open the file manager from the system menu and navigate to the jar file which you want to run.

Then, right-click on the jar app and select Properties .

From there, select Permissions and enable Allow executing file as program :

make file executable using file manager

That made the file executable.

But you have yet to select which app it should use to run the jar files.

To select an Application to start the jar files, again, click on the jar file and choose the second option Open with Other Application and choose the OpenJDK Java Runtime option:

Running Jar file in Ubuntu with double click

Now, you can start the jar application like you do with any other files by pressing the Enter key.

In my case, it was an installer and it started as it should:

running jar file in Ubuntu

Method 2: Using the Terminal

If you believe in efficiency, I’m about to show you the terminal method will complete the task in only three commands.

First, open the terminal and navigate to the directory where the jar file is located using the cd command:

Once done, use the chmod command with the +x flag to make the file executable:

And finally, you can use the Java command with the -jar flag to run the jar file:

Here’s how to set up the JAVA_HOME variable

Most of the users set the JAVA_HOME variable incorrectly. So we thought, why not make a dedicated guide to get things done correctly?

I hope you will find this guide helpful.

Источник

How to Execute and Run Java Code from the Terminal

Md. Fahim Bin Amin

Md. Fahim Bin Amin

How to Execute and Run Java Code from the Terminal

If you work with Java, you’ve probably used one of the well known text editors like Sublime Text, VS Code, Brackets, Atom, and Notepad++ as well as IDEs like Apache NetBeans and IntelliJ IDEA.

Running code in your IDE is straightforward, but you don’t often get to see how it executes your code (even though you can check the command in the terminal of course!).

However, it is good practice to know how your code actually executes and provides the output it gives you.

Many of you might have heard that experienced professional programmers also use the terminal to execute the programs. This gives them better clarity and helps them understand how the code is working, where it is returning the desired value, where the bug might be, and so on.

Whatever your purpose may be, executing Java code directly from the terminal is a very easy task.

In this article, I will show you how you can execute Java directly from your favorite terminal window. Fear not! The procedure is quite easy, and after reading the entire article you should be able to run your own Java code in the terminal.

How to Run Java Code in the Terminal

The process I am going to show you in this article is applicable to any operating system whether that is Windows, MacOS, or Linux.

Читайте также:  Using github on linux

I will be using the following Java code in the next step.

📦 Step 1 – Go to the directory where your source code is

If you have already written your Java code in an editor, then simply go into that directory. You can go straight into the directory through your file manager if you want.

How to go into the directory where the source code is: for Windows 🪟

Suppose I have the source code ( Main.java ) inside This PC > Documents folder. I can simply go there through my file explorer.

Untitled

Or, if I want, I can also go there using my terminal. I need to use cd to indicate that I want to change directory.

In this case, I can use cd «C:\Users\Md. Fahim Bin Amin\Documents» . As my user name contains white spaces, I have used » » to enclose them.

Then if I check all the files under that directory, then I will get the Main.java file as well.

I placed the Main.java file under my D drive this time. So I went in that directory using the cd command.

Screenshot-2022-03-08-022040

I get my Java file in the terminal as well.

How to go into the directory where the source code is: for Linux 🐧

You can go into the directory where you have kept your source code either by following the typical GUI way or from the terminal using the cd command as well.

Screenshot-2022-03-10-124200Screenshot-2022-03-10-124317

🧑‍💻How to Compile the Java Code

Before running our Java code, we need to compile it first. To compile a Java code/program, we get the class file. Then we need to execute/run the class file.

How to compile Java code using the terminal

We need to use the command javac file_name_with_the_extension . For example, as I want to compile my Main.java , I will use the command javac Main.java . The c in javac indicates compile.

Screenshot-2022-03-10-122312

If the compilation process is successful, then we will not get any errors.

Screenshot-2022-03-10-122345

This will create the class file we need under the same directory.

Screenshot-2022-03-10-122628

Keep in mind that we run the class file, not the .java file.

The same process is applicable for all of the operating systems out there.

Screenshot-2022-03-10-124951

🖥️ How to Run the Java Code

We run the .class file to execute the Java programs. For that, we use the command java class_file_name_without_the_extension . Like, as our .class file for this is Main.class , our command will be java Main .

Screenshot-2022-03-10-125223

The Java program has been executed successfully!

The exact same procedure is also applicable for the other operating systems as well.

Screenshot-2022-03-10-125317

🏅Bonus: How to Run a Java Program with Packages

A package basically means a folder. Earlier, I showed you how to use any regular Java code using the terminal. There, I did not use any packages inside the Java code.

Now I will show you how you can run any Java code that has packages declared within it. This time, I will be using the following Java code.

package myJavaProgram.Source; public class Main < public static void main(String[] args) < System.out.println("Hello, World!"); >>

In the first line, I have written the package as package myJavaProgram.Source . This indicates that I want to create a folder named myJavaProgram . Then, I want to create another folder under that named Source . Finally, I want to create the class file of my Java code inside the Source folder.

The directory tree looks like this: myJavaProgram > Source.

For compiling this type of Java code with the packages, we use the command javac -d . file_name_with_the_extension .

As for now, I am using the Main.java file, so I will apply the command javac -d . Main.java . This will create a folder named myJavaProgram, then create another folder named Source under the myJavaProgram folder under the directory where my source file is now.

Читайте также:  Linux iptables проброс всех портов

Screenshot-2022-03-10-134626

  • The_Directory_Where_I_Have_Kept_My_Source_Code
    • myJavaProgram folder
      • Source folder

It instantly creates the myJavaProgram folder.

Screenshot-2022-03-10-134710

Within the folder, it creates the Source folder.

Screenshot-2022-03-10-134806

Inside the Source folder, it creates our .class file. We need this file to run the Java program.

Screenshot-2022-03-10-134853

Now if we want to run the .class file, then we need to change the command a little, as we need to provide the directory of the .class file in the terminal window.

We use the command to run the Java program with packages, java directory_of_the_class_file.the_class_file_name_without_the_extension .

As I am using Main.java and I need to run the Main.class file, my command will be java myJavaProgram.Source.Main . It will run the Java code like below.

Screenshot-2022-03-10-135226

If you’re wondering why we are changing the command now, it’s because earlier, we did not declare any packages. So the Java compiler created the .class file within the directory where our source code was. So, we could get the .class file directly from there and execute the class file as well.

But if we declare packages inside the source code like this, then we are telling the compiler to create the .class file in another place (not within the directory where our source code currently is). This means that we do not get the class file directly there.

As we want to run the class file, we need to tell the compiler explicitly where the class file currently is so that it can get the class file and execute it.

If you think that you might mess up this step, then you can copy the directory directly from your Java code.

Screenshot-2022-03-10-135404

In line 1, we have declared the package directory (where we want the class file to be generated). So if we simply copy the directory and add the .class file name without the extension ( .class ) later with a period ( . ), then it satisfies the condition for executing any Java code that has packages declared in the source code.

The same process is also applicable for the other operating systems as well. I am providing screenshots from a Linux OS here:

Screenshot-2022-03-10-140017

Great job! 👏 You can now run any Java code/programs directly using a terminal. 🥳

I have also created a video where I have shown all the processes mentioned above. You can check that out here. 😁

💁‍♂️ Conclusion

I hope this article helps you run your Java programs just using the terminal.

➡️ If you want to know how to install a Java compiler for your Windows operating system, then you can check out this article.

➡️ If you want to know how to install C and C++ compilers for your Windows operating system, then you can check out this article.

➡️ If you want to know how to install Python on your Windows OS, then you can check out this article.

Thanks for reading the entire article. If it helps you then you can also check out other articles of mine at freeCodeCamp.

If you want to get in touch with me, then you can do so using Twitter, LinkedIn, and GitHub.

You can also SUBSCRIBE to my YouTube channel (Code With FahimFBA) if you want to learn various kinds of programming languages with a lot of practical examples regularly.

If you want to check out my highlights, then you can do so at my Polywork timeline.

You can also visit my website to learn more about me and what I’m working on.

Источник

Оцените статью
Adblock
detector