简体   繁体   中英

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.

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

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()

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.");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM