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 properties based on whether I am on a Windows or Unix platform). What is the safest way to do this with 100% reliability?
You can use:
System.getProperty("os.name")
P.S. You may find this code useful.
import java.util.Map;
class ShowProperties {
public static void main(String[] args) {
for (Map.Entry<Object, Object> e : System.getProperties().entrySet()) {
System.out.println(e);
}
}
}
All it does is print out all the properties provided by your Java implementations. It'll give you an idea of what you can find out about your Java environment via properties. :-)
P.P.S. (For pedants only.) I realise that java.util.Properties
has a toString
method, and thus the property iteration is redundant; however I don't like its formatting (I prefer one property a line, thanks). Just in case people ask.
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");
}
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.
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:
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.