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.

println System.properties['os.name'] //Windows 7

if (System.properties['os.name'].toLowerCase().contains('windows')) {
   System.out.println("it's Windows")
} else {
   System.out.println("it's not Windows")
}

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"));

Output Windows

Windows 7
6.1
;
C:\user\apache-groovy-sdk-2.4.10\groovy-2.4.10\bin
C:\Users\user
user
amd64

Output Linux Mint/Ubuntu

Linux
3.19.0-32-generic
:
/home/user
/home/user
user
amd64

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:

import  org.apache.commons.lang.SystemUtils 

System.out.println(SystemUtils.IS_OS_MAC)
System.out.println(SystemUtils.IS_OS_WINDOWS)
System.out.println(SystemUtils.IS_OS_UNIX)

Related Article