Pavel Janicek
Pavel Janicek

Reputation: 14738

How to get operating system in Java

I know there is such a question on SO, but I could not find it. So asking again...

I need to set up properties to my program, but I need to make it OS indipendent - running both on Windows XP and Linux (unknown distro, unknown version)

More specifically - I need to set up to the system where to find the chromedriver binary. I need something like this pseudocode:

 if (getOs() == Windows){
    System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, "chromedriver.exe");
   } else{
     System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, "chromedriver");
   }

Now I need the part for getting the OS. Thanks for help.

Upvotes: 4

Views: 7648

Answers (3)

Fiereu
Fiereu

Reputation: 1

oslib is a library that provides information about the current OS. You won't need to parse the info you get from System.getProperty("os.name");.

Note: Most operating systems are tested and supported but some are not yet implemented. For a complete list check out their Github.

Code for your specific problem:

AbstractOperatingSystem os = OperatingSystem.getOperatingSystem();

if (os.getType == OperatingSystem.WINDOWS){
    System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, "chromedriver.exe");
} else if(os.getType == OperatingSystem.LINUX) {
    System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, "chromedriver");
} else {
    throw new Exception("Unsupported OS.");
}

Upvotes: 0

Aurelien
Aurelien

Reputation: 101

You can use the utility class I wrote, you just need to copy the following class in your project

https://github.com/aurbroszniowski/os-platform-finder/blob/master/src/main/java/org/jsoftbiz/utils/OS.java

Then do:

import org.jsoftbiz.utils.OS;

    OS myOS = OS.getOs();

    myOS.getPlatformName()

    myOS.getName()
    myOS.getVersion()
    myOS.getArch()

Upvotes: 0

Henrique Miranda
Henrique Miranda

Reputation: 994

System.getProperty("os.name");
System.getProperty("os.version");
System.getProperty("os.arch");

Upvotes: 23

Related Questions