How can I detect a Unix-like OS in Java? How can I detect a Unix-like OS in Java? unix unix

How can I detect a Unix-like OS in Java?


Use the org.apache.commons.lang.SystemUtils utility class from Commons Lang, it has a nice IS_OS_UNIX constant. From the javadoc:

Is true if this is a POSIX compilant system, as in any of AIX, HP-UX, Irix, Linux, MacOSX, Solaris or SUN OS.

The field will return false if OS_NAME is null.

And the test becomes:

if (SystemUtils.IS_OS_UNIX) {    ...}

Simple, effective, easy to read, no cryptic tricks.


I've used your scheme in production code on Windows XP, Vista, Win7, Mac OS 10.3 - 10.6 and a variety of Linux distros without an issue:

    if (System.getProperty("os.name").startsWith("Windows")) {        // includes: Windows 2000,  Windows 95, Windows 98, Windows NT, Windows Vista, Windows XP    } else {        // everything else    } 

Essentially, detect Unix-like by not detecting Windows.


File.listRoots() will give you an array of the file system root directories.

If you are on a Unix-like system, then the array should contain a single entry "/" and on Windows systems you'll get something like ["C:", "D:", ...]

Edit: @chris_l: I totally forgot about mobile phones. Some digging turns up that Android returns a "/\0\0" - a slash followed by two null bytes (assumed to be a bug). Looks like we avoid false positives for the time being through luck and coincidence. Couldn't find good data on other phones, unfortunately.

It's probably not a good idea to run the same code on desktops and mobile phones regardless, but it is interesting to know. Looks like it comes down to needing to check for specific features instead of simply the system type.