Java 9 detect OS information

In this tutorial you can see how to find the OS type and some additional information about the OS. These methods are standard and reliable if you need to verify the OS on which you java code is executed. There are several exceptions in case or virtual machine or docker instance.

In this post:

Detect Linux or Windows with System properties

Detect OS additional information

Detect using Apache commons-lang

Detect Linux or Windows with System properties

The simplest method is to use os.name information and to search in the return information. For example for Windows the result would be: Windows 10. Below is simple detection between Windows and Linux.

Detect OS additional information

If you need additional information about the OS like version, separator and default directories then you can use:

//Operating system name
System.out.println(System.getProperty("os.name"));
//Operating system version
System.out.println(System.getProperty("os.version"));
//Path separator character used in java.class.path
System.out.println(System.getProperty("path.separator"));
//User working directory
System.out.println(System.getProperty("user.dir"));
//User home directory
System.out.println(System.getProperty("user.home"));
//User account name
System.out.println(System.getProperty("user.name"));
//Operating system architecture
System.out.println(System.getProperty("os.arch"));

Detect using Apache commons-lang

If you want to use third party library or the standard methods are not working in you situation you have an alternative. The best options is: Apache commons-lang project. The maven address is: Commons Lang » 2.6

It provides easy way to detect OS type. You can check the example below: