How do I programmatically determine operating system in Java?

后端 未结 19 2568
眼角桃花
眼角桃花 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条回答
  •  梦毁少年i
    2020-11-22 05:08

    If you're working in a security sensitive environment, then please read this through.

    Please refrain from ever trusting a property obtained via the System#getProperty(String) subroutine! Actually, almost every property including os.arch, os.name, and os.version isn't readonly as you'd might expect — instead, they're actually quite the opposite.

    First of all, any code with sufficient permission of invoking the System#setProperty(String, String) subroutine can modify the returned literal at will. However, that's not necessarily the primary issue here, as it can be resolved through the use of a so called SecurityManager, as described in greater detail over here.

    The actual issue is that any user is able to edit these properties when running the JAR in question (through -Dos.name=, -Dos.arch=, etc.). This means that there's no way to determine if these properties are indeed actually accurate. Because of this, here are a few additional checks to try and avoid tampering:

    // The first thing we're able to do is to query the filesystem.
    switch (java.io.File.separator)
    {
        case "/":
            // Windows is a potential candidate.
            break;
        case "\\":
            // And here it could really be anything else.
            break;
        default:
            // There's probably something really wrong here by now.
            break;
    }
    

提交回复
热议问题