How do I programmatically determine operating system in Java?

后端 未结 19 2928
眼角桃花
眼角桃花 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:12

    A small example of what you're trying to achieve would probably be a class similar to what's underneath:

    import java.util.Locale;
    
    public class OperatingSystem
    {
        private static String OS = System.getProperty("os.name", "unknown").toLowerCase(Locale.ROOT);
    
        public static boolean isWindows()
        {
            return OS.contains("win");
        }
    
        public static boolean isMac()
        {
            return OS.contains("mac");
        }
    
        public static boolean isUnix()
        {
            return OS.contains("nux");
        }
    }
    

    This particular implementation is quite reliable and should be universally applicable. Just copy and paste it into your class of choice.

提交回复
热议问题