java-detect-os
How to Detect the OS Using Java
1. Introduction
In this brief article, we’re going to see how to focus on doing OS detection in Java.
2. Implementation
One way is to make use of the System.getProperty(os.name) to obtain the name of the operating system.
The second way is to make use of SystemUtils from the Apache Commons Lang API.
Let’s see both of them in action.
2.1. Using System Properties
Let’s check it out:
public String getOperatingSystem() {
String os = System.getProperty("os.name");
// System.out.println("Using System Property: " + os);
return os;
}
2.2. SystemUtils – Apache Commons Lang
SystemUtils from Apache Commons Lang is another popular option to try for. It’s a nice API that gracefully takes care of such details.
Let’s find out the OS using SystemUtils:
public String getOperatingSystemSystemUtils() {
String os = SystemUtils.OS_NAME;
// System.out.println("Using SystemUtils: " + os);
return os;
}
3. Result
Using SystemUtils: Windows 10
Using System Property: Windows 10
4. Conclusion
As always, the code examples for this article are available over on GitHub.