Ok, I know that System.getProperty("os.name")
will give me the name of the OS I'm running under, but that's not a lot of help. What I need to know is if the OS I'm running on is a 'Unix-like' OS, I don't care if it's HP-UX, AIX, Mac OS X or whatever.
From the list of possible os.name values it seems like a quick and dirty way of detecting a 'Unix-like' OS is checking if os.name
does not contain "Windows". The false positives that will give me are OSes my code is very unlikely to encounter! Still, I'd love to know a better way if there is one.
For accessing OS use: System. getProperty("os.name") .
Type "java -version" into the Command Prompt, then press Enter on your keyboard. After a moment, your screen should display the information your computer has about Java, including what version you have installed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With