Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

unix

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.

like image 921
mluisbrown Avatar asked Jul 19 '10 15:07

mluisbrown


People also ask

Which Java method is used to detect the OS in which Java program is being run?

For accessing OS use: System. getProperty("os.name") .

How do I find out what version of Java I have Windows?

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.


2 Answers

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.

like image 106
Pascal Thivent Avatar answered Sep 28 '22 09:09

Pascal Thivent


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.

like image 34
2 revs Avatar answered Sep 28 '22 07:09

2 revs