Echo java home ubuntu

Echo java home ubuntu

  • The basics of TOGAF certification and some ways to prepare TOGAF offers architects a chance to learn the principles behind implementing an enterprise-grade software architecture, including.
  • Haskell vs. PureScript: The difference is complexity Haskell and PureScript each provide their own unique development advantages, so how should developers choose between these two .
  • A quick intro to the MACH architecture strategy While not particularly prescriptive, alignment with a MACH architecture strategy can help software teams ensure application .
  • Postman API platform will use Akita to tame rogue endpoints Akita’s discovery and observability will feed undocumented APIs into Postman’s design and testing framework to bring them into .
  • How to make use of specification-based test techniques Specification-based techniques can play a role in efficient test coverage. Choosing the right techniques can ensure thorough .
  • GitHub Copilot Chat aims to replace Googling for devs GitHub’s public beta of Copilot Chat rolls out GPT-4 integration that embeds a chat assistant into Visual Studio, but concerns .
  • 4 popular machine learning certificates to get in 2023 AWS, Google, IBM and Microsoft offer machine learning certifications that can further your career. Learn what to expect from each.
  • Navigate multi-cloud billing challenges Keeping track of cloud bills from multiple clouds or accounts can be complex. Learn how to identify multi-cloud billing .
  • 5 Google Cloud cost optimization best practices Cost is always a top priority for enterprises. For those considering Google Cloud, or current users, discover these optimization .
  • 5 steps to approach BYOD compliance policies It can be difficult to ensure BYOD endpoints are compliant because IT can’t configure them before they ship to users. Admins must.
  • Coveware: Rate of victims paying ransom continues to plummet Incident response firm Coveware said 34% of ransomware victims paid the ransom in Q2 2023, a sharp decline from last quarter and .
  • Mandiant: JumpCloud breach led to supply chain attack Mandiant researchers attribute the supply chain attack to a North Korean threat actor that abused JumpCloud’s commands framework .
  • AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
  • Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
  • Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .

Источник

Как установить JAVA HOME Linux?

движки с открытым исходным кодом для разработки игр для Linux

Советы и хитрости

Читайте также:  Css верстка на всю страницу

Java — один из самых влиятельных и популярных языков программирования. Первоначально выпущенный Sun Microsystems в 1995 году, Java является кросс-платформенным языком, который теперь является частью почти всех аспектов технологии. Вы найдете Java везде — в банковском деле, финансовых услугах, больших данных, фондовом рынке, мобильных устройствах (Android) и многом другом. Он легко входит в число лучших языков программирования и, вероятно, останется таковым еще как минимум десять лет.

В этом руководстве мы покажем один из основных и важных шагов настройки Java в вашей системе — настройку переменной среды JAVA_HOME в Linux.

Предпосылки

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

JDK против JRE

Если вас интересует Java, вы, вероятно, уже знакомы с ними. JDK означает «Комплект для разработки Java». Он содержит необходимые инструменты и библиотеки для создания и запуска (с использованием JRE) приложений Java. Если вы заинтересованы в обучении или работе над проектом Java, вам подойдет JDK.

JRE расшифровывается как «Java Runtime Environment». Этот пакет содержит инструменты и библиотеки, необходимые для запуска приложения Java. Это необходимо для запуска любой Java-программы в системе.

Обратите внимание, что JDK по умолчанию поставляется вместе с JRE. Таким образом, вам не нужно устанавливать JRE отдельно, если у вас уже установлен JDK.

Переменные среды

В Linux переменные среды содержат различную системную информацию, доступную приложениям. Информация может касаться того, как приложения работают в среде, различном поведении системы и т. д.

В зависимости от доступности переменных мы можем разделить их на 2 категории.

  • Локальные переменные среды: эти переменные задаются для каждого пользователя. Только конкретный пользователь может использовать их в своих сеансах.
  • Глобальные переменные среды: эти переменные доступны всем в системе.

JAVA_HOME

JAVA_HOME — это переменная среды. Он содержит расположение двоичных файлов Java. Многие приложения используют эту переменную среды для поиска двоичных файлов и библиотек Java.

Он может быть установлен как на локальной, так и на глобальной основе.

Настройка JAVA_HOME

Теперь, когда мы понимаем, что такое JAVA_HOME, пришло время научиться устанавливать его значение.

Во-первых, выясните версию установленной Java. Этот номер версии часто связан с двоичным путем Java.

Если Java была установлена ​​глобально, то установка, скорее всего, хранится в следующем месте.

Этот каталог содержит исполняемые файлы и библиотеки Java. Проверьте содержимое каталога.

В моем случае у меня на Ubuntu установлен OpenJDK 11 (подробнее об установке последней версии Java на Ubuntu ). Из вывода мы видим, что такие записи, как «default-java» и «java-1.11.0-openjdk-amd64», являются символическими ссылками «java-11-openjdk-amd64».

Мы собираемся установить значение JAVA_HOME на java-1.11.0-openjdk-amd64 (рекомендуется).

Обратите внимание, что эта переменная среды будет действовать только для текущего сеанса оболочки. После перезапуска вы должны установить значение еще раз вручную. Чтобы решить эту проблему, большинство оболочек поставляются с файлом конфигурации, содержащим коды и команды, которые оболочка должна выполнять при каждом запуске. В случае с bash это называется bashrc (для zsh это zshrc и т.д.).

Откройте файл в текстовом редакторе.

Читайте также:  Php div по центру

Обратите внимание, что эта переменная среды будет действовать

Теперь добавьте следующую строку в конец файла. Это пометит переменную среды, доступную для всех сеансов оболочки, и двоичные файлы, доступные непосредственно из переменной PATH.

$ export JAVA_HOME =/ usr / lib / jvm / java — 1.11.0 — openjdk — amd64

$ export PATH = $PATH : $JAVA_HOME / bin

Это пометит переменную среды, доступную для всех сеансов оболочк

Сохраните файл и закройте редактор. Чтобы изменения вступили в силу, перезагрузите файл bashrc.

Глобальная установка JAVA_HOME

В предыдущем разделе демонстрируется настройка JAVA_HOME для одной учетной записи пользователя. Это хорошая практика, поскольку каждый пользователь может предпочесть разные конфигурации. Некоторые могут даже использовать совершенно другую версию Java или разновидность Java.

Bash поставляется с глобальным файлом bashrc, который должен загружаться каждый сеанс оболочки в системе, независимо от пользователя. Объявив там расположение JAVA_HOME, мы можем сделать его доступным для всех пользователей в системе. Обратите внимание, что это не рекомендуется и должно использоваться только в определенных ситуациях.

Откройте глобальный файл bashrc в текстовом редакторе. Обратите внимание, что для настройки этого файла требуются привилегии sudo.

Откройте глобальный файл bashrc в текстовом редакторе

Теперь обновите значения JAVA_HOME и PATH.

$ export JAVA_HOME =/ usr / lib / jvm / java — 1.11.0 — openjdk — amd64

$ export PATH = $PATH : $JAVA_HOME / bin

Сохраните файл и закройте редактор

Сохраните файл и закройте редактор. Перезагрузите файл в оболочку bash, чтобы изменения вступили в силу.

Источник

How to Set JAVA_HOME Variable in Ubuntu Linux Correctly

If you are running Java programs on Ubuntu using Eclipse, Maven or Netbeans etc, you’ll need to set JAVA_HOME to your path. Otherwise, your system will complain that “java_home environment variable is not set”.

In this beginner’s tutorial, I’ll show the steps to correctly set Java Home variable on Ubuntu. The steps should be valid for most other Linux distributions as well.

The process consists of these steps:

  • Making sure Java Development Kit (JDK) is installed.
  • Finding the correct location of JDK executable.
  • Setting the JAVA_HOME variable and making the change permanent.

Step 1: Check if JDK is installed

The simplest way to check if Java Development Kit (JDK) is installed on your Linux system is by running this command:

The above command checks the version of Java compiler. If it is installed, it will show the Java version.

check java compiler ubuntu

If the command shows an error like javac command not found, you’ll have to install JDK.

java compiler check ubuntu

If Java Compiler is not installed on your system, install Java Development Kit using this command:

sudo apt install default-jdk

This will install the default Java version in your current Ubuntu version. If you need some other specific Java version, you’ll have to specify it while installing Java on Ubuntu.

Once you have made sure that Java Compiler is present on your system, it’s time to find its location.

Step 2: Get the location of JDK executable (Java Compiler)

The executable is usually located in the /usr/lib/jvm directory. I won’t left you on your own for a guessing game. Instead, let’s find out the path of the Java executable.

Читайте также:  Случайное число от массива php

Use the which command to get the location of Java Compiler executable:

The problem here is that the location it gives is actually a symbolic link. You’ll have to follow it a couple of times:

get java home path ubuntu

And when you find a path like /usr/lib/jvm/java-11-openjdk-amd64/bin/javac, you remove the /bin/javac from it to get something like /usr/lib/jvm/java-11-openjdk-amd64

An easier method is to follow the symbolic link and get to the actual executable file directly using this command:

readlink -f `which javac` | sed "s:/bin/javac::"

The readlink command follows a symbolic link. I have used ` around which java. This is called command substitution and it replaces the command with its output. Sed is then used to replace /bin/javac by nothing and thus removing it altogether.

In my example, the location of the executable file is /usr/lib/jvm/java-11-openjdk-amd64. It could be different for you. Copy the correct path you got from the above command in your system. You know, you can copy paste in the Ubuntu terminal.

Step 3: Setting JAVA_HOME variable

Now that you have got the location, use it to set the JAVA_HOME environment variable:

export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64/bin/java

Check the value of JAVA_HOME directory:

set java home ubuntu linux

Try to run your program or project in the SAME TERMINAL and see if it works.

This is not over yet. The JAVA_HOME variable you just declared is temporary. If you close the terminal or start a new session, it will be empty again.

To set JAVA_HOME variable ‘permanently’, you should add it to the bashrc file in your home directory.

You can use the Nano editor for editing files in the Linux terminal. If you do not want that and take a simple copy-paste approach, use the following commands:

Back up your bashrc file (in case you mess it, you can get it back):

Next, use the echo command to append the export command you used at the beginning of this section. Change the command below to use the correct path as displayed by your system in.

echo "export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64" >> ~/.bashrc

Verify that it has been correctly added to the end of the file:

The above tail command will show the last 3 lines of the specified file.

Here’s the entire output of the above three commands.

setting java home bashrc

Now, even if you exit the session or restart the system, the JAVA_HOME variable will still be set to the value you specified. That’s what you want, right?

Do note that if you change the default Java version in the future, you’ll have to change the value of JAVA_HOME and point it to the correct executable path.

I hope this tutorial not only helped you to set Java Home, it also taught you how you are doing it.

If you are still facing issues or have any questions or suggestions, please let me know in the comments.

Источник

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