Java's “os.name” for Windows 10?

后端 未结 5 1329
离开以前
离开以前 2020-12-01 13:49

In Java, we can see the property value of os.name to know the name of the underlying operating system: System.getProperty(\"os.name\").

For

5条回答
  •  遥遥无期
    2020-12-01 14:07

    You could also use the .contains() method and just check for the "windows" string maybe along the lines of

    if (System.getProperty("os.name").toLowerCase().contains("windows") && System.getProperty("os.name").toLowerCase().contains(windows version here [xp, 7, 8, etc]))){}
    

    If you need the windows version you could check for all versions and then assume 8.1 or 10 to move around the bug.

    if (System.getProperty("os.name").toLowerCase().contains("windows") && System.getProperty("os.name").toLowerCase().contains("xp")){
    //code for windows xp }
    
    else if (System.getProperty("os.name").toLowerCase().contains("windows") && System.getProperty("os.name").toLowerCase().contains("vista")){
    //code for windows vista
    
    else if (System.getProperty("os.name").toLowerCase().contains("windows") && System.getProperty("os.name").toLowerCase().contains("7")){
    //code for windows 7}
    
    else if (System.getProperty("os.name").toLowerCase().contains("windows") && System.getProperty("os.name").toLowerCase().contains("8")){
    //code for windows 8}
    else if (System.getProperty("os.name").toLowerCase().contains("windows") && System.getProperty("os.name").toLowerCase().contains("8.1")){
    //code for both windows 8.1 and 10
    
    }
    

    Now to explain what is going on here:

    1. the if statement is just a conditional to determine the version of windows

    2. The System.getProperty("os.name") returns the name of the os as a string

    3. The .toLowerCase() method makes that returned String lower case

    4. The .contains(String) method checks if the given input string is contained in the String it is being called on

    5. The last statement allows for different code for each os except 8.1 & 10 which would need to be handled as one block :(

提交回复
热议问题