Java system properties java home

Переменная окружения JAVA_HOME

Во многих статьях в интернете, документации к инструментам для разработки на Java и в книгах зачастую упоминается JAVA_HOME. Что же такое JAVA_HOME?

Что такое JAVA_HOME

JAVA_HOME это переменная окружения, указывающая на директорию с установленным JDK (Java Development Kit, комплект разработчика Java). JAVA_HOME это соглашение, используемое во многих программах из экосистемы Java.

Какие программы используют JAVA_HOME

  • Intellij IDEA, Eclipse, NetBeans
  • Apache Maven, Apache Ant, Gradle
  • Apache Tomcat
  • Jenkins

Некоторые игры, написанные на Java (например, Minecraft), тоже могут требовать установленной переменной JAVA_HOME.

Ошибки, связанные с JAVA_HOME

Если переменная окружения JAVA_HOME не определена, некоторые программы могут выдавать следующие ошибки:

  • Переменная среды java_home не определена
  • Cannot determine a valid Java Home
  • JAVA_HOME is set to an invalid directory
  • JAVA_HOME is not defined correctly
  • JAVA_HOME environment variable is not set
  • JAVA_HOME command not found
  • JAVA_HOME not found in your environment
  • JAVA_HOME does not point to the JDK

При появлении таких ошибок просто установите переменную JAVA_HOME

Как установить переменную окружения JAVA_HOME в Windows

Сперва вам нужно установить JDK или JRE.

  • Установите JDK, если вы занимаетесь разработкой программ на Java
  • Установите JRE, если вам нужно только запустить прикладную программу на Java

После установки JDK либо JRE запишите путь установки, он понадобится.

Читайте также:  Python run script as main

Теперь щёлкните правой кнопкой на «Мой компьютер» → «Свойства» → «Дополнительные параметры системы» → «Переменные среды…». В разделе «Системные переменные» нажмите кнопку «Создать…» и укажите следующие данные:

Имя переменной JAVA_HOME
Значение переменной Путь к директории JDK / JRE, например:
C:\Java\jdk-11.0.6

Сохраните изменения, кликнув «OK». Теперь выберите в списке переменную окружения Path и нажмите «Изменить…». В конце списка добавьте строчку со значением «%JAVA_HOME%\bin«

Для проверки откройте консоль (Win+R, cmd) и укажите последовательно укажите две команды:

Если вы правильно установили JDK/JRE и правильно установили переменные окружения, вы увидите вывод наподобие этого:

Это будет служить результатом того, что переменная JAVA_HOME установлена правильно и Java работает из командной строки.

Резюме

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

Источник

System Properties

In Properties, we examined the way an application can use Properties objects to maintain its configuration. The Java platform itself uses a Properties object to maintain its own configuration. The System class maintains a Properties object that describes the configuration of the current working environment. System properties include information about the current user, the current version of the Java runtime, and the character used to separate components of a file path name.

The following table describes some of the most important system properties

Key Meaning
«file.separator» Character that separates components of a file path. This is » / » on UNIX and » \ » on Windows.
«java.class.path» Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.
«java.home» Installation directory for Java Runtime Environment (JRE)
«java.vendor» JRE vendor name
«java.vendor.url» JRE vendor URL
«java.version» JRE version number
«line.separator» Sequence used by operating system to separate lines in text files
«os.arch» Operating system architecture
«os.name» Operating system name
«os.version» Operating system version
«path.separator» Path separator character used in java.class.path
«user.dir» User working directory
«user.home» User home directory
«user.name» User account name

Security consideration: Access to system properties can be restricted by the Security Manager. This is most often an issue in applets, which are prevented from reading some system properties, and from writing any system properties. For more on accessing system properties in applets, refer to System Properties in the Doing More With Java Rich Internet Applications lesson.

Reading System Properties

The System class has two methods used to read system properties: getProperty and getProperties .

The System class has two different versions of getProperty . Both retrieve the value of the property named in the argument list. The simpler of the two getProperty methods takes a single argument, a property key For example, to get the value of path.separator , use the following statement:

System.getProperty("path.separator");

The getProperty method returns a string containing the value of the property. If the property does not exist, this version of getProperty returns null.

The other version of getProperty requires two String arguments: the first argument is the key to look up and the second argument is a default value to return if the key cannot be found or if it has no value. For example, the following invocation of getProperty looks up the System property called subliminal.message . This is not a valid system property, so instead of returning null, this method returns the default value provided as a second argument: » Buy StayPuft Marshmallows! «

System.getProperty("subliminal.message", "Buy StayPuft Marshmallows!");

The last method provided by the System class to access property values is the getProperties method, which returns a Properties object. This object contains a complete set of system property definitions.

Writing System Properties

To modify the existing set of system properties, use System.setProperties . This method takes a Properties object that has been initialized to contain the properties to be set. This method replaces the entire set of system properties with the new set represented by the Properties object.

Warning: Changing system properties is potentially dangerous and should be done with discretion. Many system properties are not reread after start-up and are there for informational purposes. Changing some properties may have unexpected side-effects.

The next example, PropertiesTest , creates a Properties object and initializes it from myProperties.txt .

subliminal.message=Buy StayPuft Marshmallows!

PropertiesTest then uses System.setProperties to install the new Properties objects as the current set of system properties.

import java.io.FileInputStream; import java.util.Properties; public class PropertiesTest < public static void main(String[] args) throws Exception < // set up new properties object // from file "myProperties.txt" FileInputStream propFile = new FileInputStream( "myProperties.txt"); Properties p = new Properties(System.getProperties()); p.load(propFile); // set the system properties System.setProperties(p); // display new properties System.getProperties().list(System.out); >>

Note how PropertiesTest creates the Properties object, p , which is used as the argument to setProperties :

Properties p = new Properties(System.getProperties());

This statement initializes the new properties object, p , with the current set of system properties, which in the case of this small application, is the set of properties initialized by the runtime system. Then the application loads additional properties into p from the file myProperties.txt and sets the system properties to p . This has the effect of adding the properties listed in myProperties.txt to the set of properties created by the runtime system at startup. Note that an application can create p without any default Properties object, like this:

Properties p = new Properties();

Also note that the value of system properties can be overwritten! For example, if myProperties.txt contains the following line, the java.vendor system property will be overwritten:

java.vendor=Acme Software Company

In general, be careful not to overwrite system properties.

The setProperties method changes the set of system properties for the current running application. These changes are not persistent. That is, changing the system properties within an application will not affect future invocations of the Java interpreter for this or any other application. The runtime system re-initializes the system properties each time its starts up. If changes to system properties are to be persistent, then the application must write the values to some file before exiting and read them in again upon startup.

Источник

How to Setup, Configure JAVA_HOME and JRE_HOME Environment Variables on Windows?

In order to run Java application you need to have first installed Java on your Mac or Windows laptop or desktop.

It’s absolutely required to complete Java setup right way for your production & development applications. If you are a first time Java user then first step is to go to official Oracle website and download JDK.

Below detailed steps will help also if you have below questions:

  • How to fix JAVA_HOME error while starting Tomcat Server?
  • Why i’m getting jre_home is not defined correctly tomcat error?
  • How to set jre_home environment variable?
  • jre_home on windows
  • Difference between java_home vs jre_home
  • How to set jre_home via command line?

In this tutorial we will discuss how to install Java, setup JRE_HOME & JAVA_HOME environment variables on Windows platform only. For Mac and Linux, I’ll publish another tutorial with all detailed steps later.

Let’s get started

Step-1

Configure JAVA_HOME / JRE_HOME Environment Variables

  • Go to official Oracle site and Download JDK binary
  • Click on Java Download
  • Accept License Agreement
  • Download binary next to Windows x64

Step-2

  • Double click on .exe file and it will install JDK and JRE both on your Windows Laptop/Desktop
  • By default it will install JDK and JRE at location: C:\Program Files\Java folder

Step-3

  • Now minimize all windows and you will see Desktop icon (check this screenshot)
  • Right click on it
  • Click on Properties
  • Click on Advanced System Settings link as you in above diagram

Step-4

Step-5

  • New Pop-up Window will appear
  • Click on New…
  • Enter JAVA_HOME as variable name and C:\Program Files\Java\jdk1.8.0_121 as Value
  • Enter JRE_HOME as variable name and C:\Program Files\Java\jre1.8.0_121 as Value
  • Click OK button
  • Exit System Properties window

At this time, you are all set.

How to verify?

How to verify if JAVA_HOME and JRE_HOME environment variables setup correctly or not?

  • Just open command prompt
  • Type java -version
  • It will print installed Java details as shown below

That’s it. Let me know if you face any issue installing Java on your laptop. Make sure to update Java version number as per your installation in above steps. Happy coding and happy open sourcing.

What is a difference Between JRE and JDK?

Ideally JRE provides runtime environment for your application. While running your development or production environment, you just need JRE.

On other end, while you are developing Java application , JDK provides more debugging and development functionalities which wont part of JRE.

If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion.

Suggested Articles.

Источник

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