Linux run java app

How to Run Java from Command-line in Linux

Java is the world’s popular software development platform that James Gosling develops. It is designed to support multiple platforms like Linux, macOS and Windows. Mobile and Desktop applications can also be developed using Java language.

Java language is one of the most popular high-level object-oriented programming languages. It comes with a simple syntax and easily understandable for beginners, as it is very secure and economical to use. Java is the platform-independent software, and it also provides an auto garbage collection facility.

How to Run Java through Command-line

To run the java program in Linux, we need to verify if Java Development Kit (JDK) is available in the system and its version.

To confirm it, type the following command:

(Javac command-line tool is used for the compilation of java programs)

The Javac command tool is not available in my system. We have multiple commands to download it, as mentioned in the above image.

Let’s go with the default-jdk command to get it:

To verify the installation of javac, type:

Now, write a Java program in the text file and save it with .java extension.

Suppose I created a file named “testing.java” and write a simple program in it:

(Keep in mind that your class name should be the same as the file name)

Compile the testing.java file on the terminal using the javac command:

Now, execute the Java program by calling its class name in the terminal:

Conclusion

Java is the high-level language of the modern era supported by the Java Development Kit (JDK). JDK is a package that helps to run java and is used for the development of software packages.

Java language comes with a simple syntax that is easy to get for beginners, and it is one of the most usable object-oriented programming languages.

We have seen in this article that how to install and run Java applications on the terminal.

About the author

Syeda Wardah Batool

I am a Software Engineer Graduate and Self Motivated Linux writer. I also love to read latest Linux books. Moreover, in my free time, i love to read books on Personal development.

Читайте также:  Oracle linux лицензионное соглашение

Источник

How to Run Java Programs in Ubuntu

So, you have started learning Java programming? That’s good.

And you want to run the java programs on your Linux system? Even better.

Let me show how to run Java in terminal in Ubuntu and other Linux distributions.

Running Java programs in Ubuntu

Let’s go in proper steps here.

Step 1: Install Java compiler

To run a Java program, you need to compile the program first. You need Java compiler for this purpose.

The Java compiler is part of JDK (Java Development Kit). You need to install JDK in order to compile and run Java programs.

First, check if you already have Java Compiler installed on your system:

If you see an error like “Command ‘javac’ not found, but can be installed with”, this means you need to install Java Development Kit.

java compiler check ubuntu

The simplest way to install JDK on Ubuntu is to go with the default offering from Ubuntu:

sudo apt install default-jdk

You’ll be asked to enter your account’s password. When you type the password, nothing is seen on the screen. That is normal. Just enter your password blindly. When asked, press the enter key or Y key.

install jdk ubuntu

The above command should work for other Debian and Ubuntu based distributions like Linux Mint, elementary OS etc. For other distributions, use your distribution’s package manager. The package name could also be different.

Once installed, verify that javac is available now.

java compiler ubuntu

Step 2: Compile Java program in Linux

You need to have a Java program file for this reason. Let’s say you create a new Java program file named HelloWorld.java and it has the following content:

You can use Nano editor in terminal or Gedit graphical text editor for writing your Java programs.

If there is no error, the above command produces no output.

When you compile the Java program, it generates a .class file with the class name you used in your program. You have to run this class file.

Step 3: Run the Java class file

You do not need to specify the class extension here. Just the name of the class. And this time, you use the command java, not javac.

This will print Hello World on the screen for my program.

running java programs in linux terminal

And that’s how you run a Java program in the Linux terminal.

This was the simplest of the example. The sample program had just one class. The Java compiler creates a class file for each class in your program. Things get complicated for bigger programs and projects.

Читайте также:  Linux bin install java

This is why I advise installing Eclipse on Ubuntu for proper Java programming. It is easier to program in an IDE.

I hope you find this tutorial helpful. Questions or suggestions? The comment section is all yours.

Источник

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

Читайте также:  Linux kernel intel driver

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите 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.

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.

Источник

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