Run java program from linux

How To Compile and Run Java Program in Linux

Today I’ll explain how to compile and run Java code on Linux environment.

Personally, I like Ubuntu, that’s why I’ll show you how to do it there.

First of all, you have to be sure that Java is installed on your machine.

Correct output is:

If it’s not installed you can do it easy:

Now change directory to your project source folder.

Inside of my project I have a class Car, that I wrote when I talked about the transient keyword in Java.

It looks like this:

How to Compile Java Program

To compile this class I call Linux Java compiler:

If everything was OK you should find a new file Car.class near Car.java.

Our class is compiled, the next step is to run compiled Java class on Ubuntu.

How to Run Java Program

In the previous section, I compiled Java code in Linux.

Now I’m going to show how to run Java program.

Just point Java to compiled class like this:

Note that you should run Java class from the source folder.

For example, if I change directory to project (one level upper than src folder).

and try to run the same class:

So you have to be sure that you’re running your Java code on Ubuntu from the source folder.

For compiling process it doesn’t matter.

As you can see it’s easy to compile and run Java on Linux.

Personally, I prefer Java programming on Linux instead of Windows.

I think Java developers should know at least basic Linux commands.

Источник

How to Run Java from Command-line in Linux

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.

Читайте также:  Как удалить временные файлы linux

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

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.

Источник

Работа с Java в командной строке

От простого к .

Каждая программа обычно содержится в отдельном каталоге. Я придерживаюсь правила создавать в этом каталоге по крайней мере две папки: src и bin. В первой содержатся исходные коды, во второй — результат компиляции. В данных папках будет структура каталогов, зависящая от пакетов.

Один файл

Можно сделать и без лишних папок.
Берем сам файл HelloWorld.java.
Переходим в каталог, где лежит данный файл, и выполняем команды.
В данной папке появится файл HelloWorld.class. Значит программа скомпилирована. Чтобы запустить

Отделяем бинарные файлы от исходников

Теперь сделаем тоже самое, но с каталогами. Создадим каталог HelloWorld и в нем две папки src и bin.
Компилируем
Здесь мы указали, что бинарные файлы будут сохраняться в отдельную папку bin и не путаться с исходниками.

Используем пакеты

А то, вдруг, программа перестанет быть просто HelloWorld-ом. Пакетам лучше давать понятное и уникальное имя. Это позволит добавить данную программу в другой проект без конфликта имен. Прочитав некоторые статьи, можно подумать, что для имени пакета обязательно нужен домен. Это не так. Домены — это удобный способ добиться уникальности. Если своего домена нет, воспользуйтесь аккаунтом на сайте (например, ru.habrahabr.mylogin). Он будет уникальным. Учтите, что имена пакетов должны быть в нижнем регистре. И избегайте использования спецсимволов. Проблемы возникают из-за разных платформ и файловых систем.

Поместим наш класс в пакет с именем com.qwertovsky.helloworld. Для этого добавим в начало файла строчку
В каталоге src создадим дополнительные каталоги, чтобы путь к файлу выглядел так: src/com/qwertovsky/helloworld/HelloWorld.java.
Компилируем
В каталоге bin автоматически создастся структура каталогов как и в src.

Если в программе несколько файлов

HelloWorld.java
Calculator.java
Adder.java

Ошибка возникла из-за того, что для компиляции нужны файлы с исходными кодами классов, которые используются (класс Calculator). Надо указать компилятору каталог с файлами с помощью ключа -sourcepath.
Компилируем

Если удивляет результат

Есть возможность запустить отладчик. Для этого существует jdb.
Сначала компилируем с ключом -g, чтобы у отладчика была информация.

Отладчик запускает свой внутренний терминал для ввода команд. Справку по последним можно вывести с помощью команды help.
Указываем точку прерывания на 9 строке в классе Calculator

Запускаем на выполнение.

Чтобы соориентироваться можно вывести кусок исходного кода, где в данный момент находится курссор.

Узнаем, что из себя представляет переменная а.

Выполним код в текущей строке и увидим, что sum стала равняться 2.

Поднимемся из класса Adder в вызвавший его класс Calculator.

Удаляем точку прерывания

Можно избежать захода в методы, используя команду next.

Проверяем значение выражения и завершаем выполнение.

Хорошо бы протестировать

Запускаем. В качестве разделителя нескольких путей в classpath в Windows используется ‘;’, в Linux — ‘:’. В консоли Cygwin не работают оба разделителя. Возможно, должен работать ‘;’, но он воспринимается как разделитель команд.

Создадим библиотеку

Класс Calculator оказался полезным и может быть использован во многих проектах. Перенесем всё, что касается класса Calculator в отдельный проект.

Измените также назавания пакетов в исходных текстах. В HelloWorld.java нужно будет добавить строку

Делаем архив jar

С помощью ключа -C мы запустили программу в каталоге bin.

Надо узнать, что у библиотеки внутри

Можно распаковать архив zip-распаковщиком и посмотреть, какие классы есть в библиотеке.
Информацию о любом классе можно получить с помощью дизассемблера javap.

Из результата видно, что класс содержит кроме пустого конструктора, ещё один метод sum, внутри которого в цикле вызывается метод add класса Adder. По завершении метода sum, вызывается Adder.getSum().
Без ключа -c программа выдаст только список переменных и методов (если использовать -private, то всех).

Читайте также:  Что такое runlevel linux

Лучше снабдить библиотеку документацией

Изменим для этого класс калькулятора.

Документацию можно создать следующей командой. При ошибке программа выдаст список возможных опций.

В результате получиться следующее

Можно подписать jar-архив

Если требуется подписать свою библиотеку цифровой подписью, на помощь придут keytool и jarsigner.
Генерируем подпись.

Генерируем Certificate Signing Request (CSR)

Содержимое полученного файла отправляем в центр сертификации. От центра сертификации получаем сертификат. Сохраняем его в файле (например, qwertokey.cer) и импортируем в хранилище

Файл qwertokey.cer отправляем всем, кто хочет проверить архив. Проверяется он так

Использование библиотеки

Есть программа HelloWorld, которая использует библиотечный класс Calculator. Чтобы скомпилировать и запустить программу, нужно присоединить библиотеку.
Компилируем

Собираем программу

Это можно сделать по-разному.

Первый способ

Здесь есть тонкости.
В строке

не должно быть пробелов в конце.
Вторая тонкость описана в [3]: в этой же строке должен стоять перенос на следующую строку. Это если манифест помещается в архив сторонним архиватором.
Программа jar не включит в манифест последнюю строку из манифеста, если в конце не стоит перенос строки.
Ещё момент: в манифесте не должно быть пустых строк между строками. Будет выдана ошибка «java.io.IOException: invalid manifest format».

При использовании команды echo надо следить только за пробелом в конце строки с main-class.

Второй способ

В данном способе избегаем ошибки с пробелом в main-class.

Третий способ

Включили код нужной библиотеки в исполняемый файл.

Запуск исполняемого jar-файла

Файл calculator.jar исполняемым не является. А вот helloworld.jar можно запустить.
Если архив был создан первыми двумя способами, то рядом с ним в одном каталоге должна находится папка lib с файлом calculator.jar. Такие ограничения из-за того, что в манифесте в class-path указан путь относительно исполняемого файла.

При использовании третьего способа нужные библиотеки включаются в исполняемый файл. Держать рядом нужные библиотеки не требуется. Запускается аналогично.

Как быть с приложениями JavaEE

Аналогично. Только библиотеки для компиляции нужно брать у сервера приложений, который используется. Если я использую JBoss, то для компиляции сервлета мне нужно будет выполнить примерно следующее

Структура архива JavaEE-приложения должна соответствовать определенному формату. Например

Способы запуска приложения на самом сервере с помощью командной строки для каждого сервера различны.

Надеюсь, данная статья станет для кого-нибудь шпаргалкой для работы с Java в командной строке. Данные навыки помогут понять содержание и смысл Ant-скриптов и ответить на собеседовании на более каверзные вопросы, чем «Какая IDE Вам больше нравится?».

Источник

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.

Читайте также:  Как убрать предложение загрузки windows

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.

Источник

How to Run Java Programs in Ubuntu

Last updated September 7, 2021 By Abhishek Prakash Leave a Comment

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.

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

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.

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.

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.

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.

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.

Like what you read? Please share it with others.

Источник

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