- Методы getproperty () и getproperties () системного класса в Java
- System Properties
- Reading System Properties
- Writing System Properties
- Java System.getProperty vs System.getenv
- Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
- 1. Introduction
- 2. Using System.getProperty()
- 3. Using System.getenv()
- 4. The Differences
- 5. Conclusion
Методы getproperty () и getproperties () системного класса в Java
Класс System в Java имеет два метода, используемых для чтения системных свойств:
- getProperty: Класс System имеет две разные версии getProperty. Оба получают значение свойства, указанного в списке аргументов. Более простой из двух методов getProperty принимает один аргумент.
- getProperties: метод java.lang.System.getProperties () определяет текущие системные свойства.
Описание методов
- getProperty (String key): метод java.lang.System.getProperty (String key) возвращает строку, содержащую значение свойства. Если свойство не существует, эта версия getProperty возвращает значение NULL.
Это основано на паре ключ-значение, как указано в таблице ниже.
Синтаксис:
Реализация :
// Java-программа, иллюстрирующая работу метода getProperty (String key)
public class NewClass
public static void main(String[] args)
// Печать имени системного свойства
System.out.println( «user.dir: » +System.getProperty( «user.dir» ));
// Извлекает набор свойств с ключом ‘home’
System.out.println( «home: » +System.getProperty( «home» ));
// В результате получается значение Null, поскольку свойство отсутствует
// Выводим имя операционной системы
System.out.println( «os.name: » +System.getProperty( «os.name» ));
// Печать ‘JAVA Runtime version’
System.out.println( «version: » +System.getProperty( «java.runtime.version» ));
// Печать свойства name
System.out.println( «name: » +System.getProperty( «name» ));
// В результате получается значение Null, поскольку свойство отсутствует
Выход :
getProperty (ключ String, определение String): java.lang.System.getProperty (ключ String, определение String) позволяет задать определение аргумента, т.е. можно задать значение по умолчанию для определенного ключа.
Синтаксис:
Реализация :
// Java-программа, иллюстрирующая работу
// getProperty (String key, String definition) метод
public class NewClass
public static void main(String[] args)
// использование метода getProperty (ключ String, определение String)
// Здесь key = «Hello» и System Property = «Geeks»
System.out.println( «Hello property : «
+ System.getProperty( «Hello» , «Geeks» ));
// Здесь key = «Geek» и System Property = «For Geeks»
+ System.getProperty( «System» , «For Geeks» ));
// Здесь key = «Property» и System Property = null
Выход :
getProperties ():java.lang.System.getProperties () извлекает текущие свойства, которые JVM в вашей Системе получает от вашей операционной системы. Текущие системные свойства возвращаются как объект Properties для использования методом getProperties (). Если такой набор свойств отсутствует, сначала создается набор системы, а затем инициализируется.
Можно также изменить существующий набор системных свойств, используя метод System.setProperties (). В файле свойств есть номер пары ключ-значение , некоторые из которых следующие:
Синтаксис:
Реализация :
// Java-программа, иллюстрирующая работу метода getProperties ()
public class NewClass
public static void main(String[] args)
/ * Использование метода getProperties ()
Системный класс относится к JVM, на которой вы компилируете свой код JAVA
getProperty выбирает фактические свойства
что JVM на вашем Sysytem получает от вашей операционной системы
System.out.println( «Following are the JVM information of your OS :» );
Properties jvm = System.getProperties();
Вывод: Нажмите здесь, чтобы увидеть вывод
Важные моменты:
- java.lang.System.getProperty (String key): выбирает только те свойства — значения, которые вы укажете с помощью ключа (связанного с этим конкретным значением, которое вы хотите).
- java.lang.System.getProperty (String key, String defining): помогает вам создавать ваши собственные наборы значений ключей, которые вы хотите.
- java.lang.System.getProperties (): извлекает все свойства — значения, которые JVM в вашей системе получает из операционной системы.
Эта статья предоставлена Мохит Гупта 🙂 . Если вы как GeeksforGeeks и хотели бы внести свой вклад, вы также можете написать статью с помощью contribute.geeksforgeeks.org или по почте статьи contribute@geeksforgeeks.org. Смотрите свою статью, появляющуюся на главной странице GeeksforGeeks, и помогите другим вундеркиндам.
Пожалуйста, пишите комментарии, если вы обнаружите что-то неправильное или вы хотите поделиться дополнительной информацией по обсуждаемой выше теме.
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 |
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:
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! «
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.
The next example, PropertiesTest , creates a Properties object and initializes it from myProperties.txt .
PropertiesTest then uses System.setProperties to install the new Properties objects as the current set of system properties.
Note how PropertiesTest creates the Properties object, p , which is used as the argument to setProperties :
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:
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:
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.
Java System.getProperty vs System.getenv
Last modified: July 20, 2020
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
If you have a few years of experience in the Java ecosystem, and you’re interested in sharing that experience with the community (and getting paid for your work of course), have a look at the «Write for Us» page. Cheers, Eugen
1. Introduction
The package java.lang is automatically imported when in a Java application. This package contains many commonly used classes from NullPointerException to Object, Math, and String.
The java.lang.System class is a final class, meaning that we cannot subclass it, therefore all methods are static.
We are going to look at the differences between two System methods for reading system properties and environment variables.
These methods are getProperty and getenv.
2. Using System.getProperty()
The Java platform uses a Properties object to provide information about the local system and configuration and we call it System Properties.
System Properties include information such as the current user, the current version of the Java runtime, and file path-name separator.
In the below code, we use System.getProperty(“log_dir”) to read the value of the property log_dir. We also make use of the default value parameter so if the property does not exist, getProperty returns of /tmp/log:
To update System Properties at runtime, use the method System.setProperty method:
We can pass our own properties or configurations values to the application using the propertyName command line argument in the format:
Setting the property of foo with a value of bar in app.jar:
System.getProperty will always return a String.
3. Using System.getenv()
Environment Variables are key/value pairs like Properties. Many Operating Systems use Environment Variables to allow configuration information to be passed into applications.
The way to set an environment variable differs from one operating system to another. For example, in Windows, we use a System Utility application from the control panel while in Unix we use shell scripts.
When creating a process, by default it inherits a clone environment of its parent process.
The following code snippet shows using a lambda expression to print all Environment Variables.
getenv() returns a read-only Map. Trying to add values to the map throws an UnsupportedOperationException.
To obtain a single variable, call getenv with the variable name:
On the other hand, we can create another process from our application and add new variables to its environment.
To create a new process in Java, we use ProcessBuilder class which has a method called environment. This method returns a Map but this time the map is not read-only, meaning we can add elements to it:
4. The Differences
Although both are essentially maps that provide String values for String keys, let’s look at a few differences:
- We can update Properties at runtime while Environment Variables are an immutable copy of the Operating System’s variables.
- Properties are contained only within Java platform while Environment Variables are global at the Operating System level – available to all applications running on the same machine.
- Properties must exist when packaging the application but we can create Environment Variables on the Operating System at almost any point.
5. Conclusion
Although conceptually similar, the application of both Properties and Environment Variables are quite different.
The choice between the options is often a question of scope. Using Environment Variables, the same application can be deployed to multiple machines to run different instances and can be configured at the Operating System level or even in AWS or Azure Consoles. Removing the needing to rebuild application to update config.
Always remember that getProperty follows camel-case convention and getenv does not.