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
TL;DR
For accessing OS use: System.getProperty("os.name")
.
But why not create a utility class, make it reusable! And probably much faster on multiple calls. Clean, clear, faster!
Create a Util class for such utility functions. Then create public enums for each operating system type.
public class Util {
public enum OS {
WINDOWS, LINUX, MAC, SOLARIS
};// Operating systems.
private static OS os = null;
public static OS getOS() {
if (os == null) {
String operSys = System.getProperty("os.name").toLowerCase();
if (operSys.contains("win")) {
os = OS.WINDOWS;
} else if (operSys.contains("nix") || operSys.contains("nux")
|| operSys.contains("aix")) {
os = OS.LINUX;
} else if (operSys.contains("mac")) {
os = OS.MAC;
} else if (operSys.contains("sunos")) {
os = OS.SOLARIS;
}
}
return os;
}
}
Now, you can easily invoke class from any class as follows,(P.S. Since we declared os variable as static, it will consume time only once to identify the system type, then it can be used until your application halts. )
switch (Util.getOS()) {
case WINDOWS:
//do windows stuff
break;
case LINUX:
and That is it!