How do I programmatically determine operating system in Java?

后端 未结 19 2532
眼角桃花
眼角桃花 2020-11-22 04:56

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

19条回答
  •  广开言路
    2020-11-22 05:29

    Oct. 2008:

    I would recommend to cache it in a static variable:

    public static final class OsUtils
    {
       private static String OS = null;
       public static String getOsName()
       {
          if(OS == null) { OS = System.getProperty("os.name"); }
          return OS;
       }
       public static boolean isWindows()
       {
          return getOsName().startsWith("Windows");
       }
    
       public static boolean isUnix() // and so on
    }
    

    That way, every time you ask for the Os, you do not fetch the property more than once in the lifetime of your application.


    February 2016: 7+ years later:

    There is a bug with Windows 10 (which did not exist at the time of the original answer).
    See "Java's “os.name” for Windows 10?"

提交回复
热议问题