Java system property get and set
In this chapter you will learn:
- Get/set system property
- Predefined System properties
- Get the system properties
- Set a system properties
- Get the system environment
Get/set system property
System properties are the properties related to Java runtime system.
For example, each Java runtime may have different operation system, may have
different Java SDK directories. We can store and access those information through
System
class.
Here is the list of methods from System class we can use to get the system properties.
static String clearProperty(String key)
Removes the system property by name.static String getenv(String name)
Gets the value of the specified environment variable.static Properties getProperties()
Determines the current system properties.static String getProperty(String key)
Gets the system property.static String getProperty(String key, String def)
Gets the system property.static void setProperties(Properties props)
Sets the system properties to the Properties argument.static String setProperty(String key, String value)
Sets the system property.
Predefined System properties
The following properties are available:
- file.separator
- java.class.path
- java.class.version
- java.compiler
- java.ext.dirs
- java.home
- java.io.tmpdir
- java.library.path
- java.specification.name
- java.specification.vendor
- java.specification.version
- java.vendor
- java.vendor.url
- java.version
- java.vm.name
- java.vm.specification.name
- java.vm.specification.vendor
- java.vm.specification.version
- java.vm.vendor
- java.vm.version
- line.separator
- os.arch
- os.name
- os.version
- path.separator
- user.dir
- user.home
- user.name
Get the system properties
The following code gets the system property and checks if we are running on windows system.
public class Main {
public static void main(String[] args) {
String strOSName = System.getProperty("os.name");
if (strOSName != null) {
if (strOSName.toLowerCase().indexOf("windows") != -1)
System.out.println("Windows");
else//from j a v a 2 s. co m
System.out.print("not windows");
}
}
}
Set a system properties
The following code sets and creates new system properties using setProperty
method and then calls the getProperty
to get the properties.
public class Main {
/* ja v a 2 s . com*/
public static void main(String args[]) {
System.setProperty("myKey", "myValue");
System.out.println(System.getProperty("myKey"));
}
}
The output:
Get the system environment
static Map<String,String> getenv()
Returns an unmodifiable string map view of the current system environment.
public class Main {
// ja v a 2 s.c o m
public static void main(String args[]) {
System.out.println(System.getenv());
}
}
The output:
Next chapter...
What you will learn in the next chapter:
- How to get current time in nano seconds
- How to get current time in millis seconds
- How to time the performance of a for loop