Running java application on ubuntu

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.

java version "1.8.0_144" Java(TM) SE Runtime Environment (build 1.8.0_144-b01) Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)

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

sudo add-apt-repository ppa:webupd8team/java sudo apt-get update sudo apt-get install oracle-java8-installer

Now change directory to your project source folder.

cd ~/workspace/explainjava/src/

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

package com.explainjava; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class Car implements Serializable < private static final long serialVersionUID = 1L; private String name; private transient String color; public Car(String name, String color) < this.name = name; this.color = color; >@Override public String toString() < return "Car'; > public static void main(String args[]) throws Exception < Car car = new Car("BMW", "red"); // serialize object and save it to file ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("carStorage")); outputStream.writeObject(car); outputStream.close(); // reading read file and deserialize bytes to object ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("carStorage")); Car deserializedCar = (Car) inputStream.readObject(); System.out.println(deserializedCar); >>

How to Compile Java Program

To compile this class I call Linux Java compiler:

javac com/explainjava/Car.java

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

-rw-rw-r-- 1 dshvechikov dshvechikov 1447 dec 5 09:06 Car.class -rw-rw-r-- 1 dshvechikov dshvechikov 1236 nov 17 15:29 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:

java src.com.explainjava.Car
Error: Could not find or load main class src.com.explainjava.Car

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 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.

Читайте также:  Convert html to docx php

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.

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

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

Источник

Your First Java Program in the Ubuntu Terminal

Ubuntu Java Development

Ubuntu Java Development

If you are new to Java Programming in the Ubuntu operating system, this simple tutorial will guide you along in writing and compiling your first Java Hello World program. The applications that you need for this purpose include the Java Runtime Environment and the Java Development Kit. This article covers the installation of these two through the Ubuntu command line. You can then write your first program in a text editor such as gedit, nano or even some graphical text writing tool. You will then compile your program in order to create a class that you can then execute in order to run your Java program.

We have run the commands and procedures mentioned in this article on an Ubuntu 18.04 LTS system.

Java Installation

In order to compile and run a basic Java program, you need to have the following two software installed on your Ubuntu system:

Let us first open the Ubuntu command line, the Terminal, in order to install these two. You can open the Terminal either through the system Dash or the Ctrl+alt+T shortcut.

Читайте также:  Python tkinter размеры окна

Since we will be installing Java through the apt utility, first let us update our apt repositories through the following command:

The next thing is to run the following command:

This will ensure either Java Runtime Environment is already installed on your system or not. If yes, it will also let you know which version of Java you have on your system.

In my case, the output shows that I do not have Java installed on my system yet.

Java version

In order to install the Java Runtime Environment on your system, run the following command as root:

Install Java default JRE

The system will prompt a Y/n option for you to continue installation. Please enter Y to continue, after which JRE will be installed on your system.

You can then check the installed version of Java as follows:

Check Java version again

After installing the JRE, let us check if we have the Java Development Kit installed on our system or not. This can be done by checking the version of your Java Compiler, javac, as follows:

javac version

The above output shows that I need to install the Java compiler or the JDK on my system.

You can install it through the following command as root:

$ sudo apt install default-jdk

Install Java JDK

The system will prompt a Y/n option for you to continue installation. Please enter Y to continue, after which JDK will be installed on your system.

You can then check the installed version of the Java Compiler as follows:

Check java compiler version again

The basic installations you need to have before running a Java program are now complete.

Your First Java Program

Before starting to write Java programs, it is best practice to make a dedicated directory for all your Java related work. I am creating such a directory through the following command in my home folder:

Then move to that directory as follows:

Create project directory

The next step is to write your first Java program. You can write it in any of your favorite text editors. Here, I am using the gedit editor to write the program. Run the following command in order to open a new java file in the gedit editor:

Open new Java source code file

Then copy the following code in your file:

Java program code

This program is simply intended to print “Hello World” on your screen.

Save the file and close it.

Then is the time to compile your first program through the Java compiler as follows:

The ls command will show that the compiler will create a class based on the class in your Java code:

Compile java sourcecode

In order to run the compiled program, run the following program:

Running Japa program

In this article, you have learned to install both the Java Runtime Environment and the Java Development Kit used to compile and run your java programs. We also wrote a simple Hello World program in Java and ran to see if you and your system are ready to move to the more complex world of Java Programming.

About This Site

Vitux.com aims to become a Linux compendium with lots of unique and up to date tutorials.

Latest Tutorials

Источник

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