I would like to determine the operating system of the host that my Java program is running programmatically (for example: I would like to be able to load different propertie
If you're interested in how an open source project does stuff like this, you can check out the Terracotta class (Os.java) that handles this junk here:
And you can see a similar class to handle JVM versions (Vm.java and VmVersion.java) here:
Just use com.sun.javafx.util.Utils
as below.
if ( Utils.isWindows()){
// LOGIC HERE
}
OR USE
boolean isWindows = OSInfo.getOSType().equals(OSInfo.OSType.WINDOWS);
if (isWindows){
// YOUR LOGIC HERE
}
I find that the OS Utils from Swingx does the job.
Oct. 2008:
I would recommend to cache it in a static variable:
public static final class OsUtils
{
private static String OS = null;
public static String getOsName()
{
if(OS == null) { OS = System.getProperty("os.name"); }
return OS;
}
public static boolean isWindows()
{
return getOsName().startsWith("Windows");
}
public static boolean isUnix() // and so on
}
That way, every time you ask for the Os, you do not fetch the property more than once in the lifetime of your application.
February 2016: 7+ years later:
There is a bug with Windows 10 (which did not exist at the time of the original answer).
See "Java's “os.name” for Windows 10?"
As indicated in other answers, System.getProperty provides the raw data. However, the Apache Commons Lang component provides a wrapper for java.lang.System with handy properties like SystemUtils.IS_OS_WINDOWS, much like the aforementioned Swingx OS util.
String osName = System.getProperty("os.name");
System.out.println("Operating system " + osName);