How do I programmatically determine operating system in Java?

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 properties based on whether I am on a Windows or Unix platform). What is the safest way to do this with 100% reliability?


Asked by: Marcus325 | Posted: 28-01-2022






Answer 1

You can use:

System.getProperty("os.name")

P.S. You may find this code useful:

class ShowProperties {
    public static void main(String[] args) {
        System.getProperties().list(System.out);
    }
}

All it does is print out all the properties provided by your Java implementations. It'll give you an idea of what you can find out about your Java environment via properties. :-)

Answered by: Kristian589 | Posted: 01-03-2022



Answer 2

As indicated in other answers, System.getProperty provides the raw data. However, the Apache Commons Lang component provides a wrapper for java.lang.System with handy properties like SystemUtils.IS_OS_WINDOWS, much like the aforementioned Swingx OS util.

Answered by: Arthur191 | Posted: 01-03-2022



Answer 3

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?"

Answered by: Ted775 | Posted: 01-03-2022



Answer 4

some of the links in the answers above seem to be broken. I have added pointers to current source code in the code below and offer an approach for handling the check with an enum as an answer so that a switch statement can be used when evaluating the result:

OsCheck.OSType ostype=OsCheck.getOperatingSystemType();
switch (ostype) {
    case Windows: break;
    case MacOS: break;
    case Linux: break;
    case Other: break;
}

The helper class is:

/**
 * helper class to check the operating system this Java VM runs in
 *
 * please keep the notes below as a pseudo-license
 *
 * http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java
 * compare to http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/Os.java
 * http://www.docjar.com/html/api/org/apache/commons/lang/SystemUtils.java.html
 */
import java.util.Locale;
public static final class OsCheck {
  /**
   * types of Operating Systems
   */
  public enum OSType {
    Windows, MacOS, Linux, Other
  };

  // cached result of OS detection
  protected static OSType detectedOS;

  /**
   * detect the operating system from the os.name System property and cache
   * the result
   * 
   * @returns - the operating system detected
   */
  public static OSType getOperatingSystemType() {
    if (detectedOS == null) {
      String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
      if ((OS.indexOf("mac") >= 0) || (OS.indexOf("darwin") >= 0)) {
        detectedOS = OSType.MacOS;
      } else if (OS.indexOf("win") >= 0) {
        detectedOS = OSType.Windows;
      } else if (OS.indexOf("nux") >= 0) {
        detectedOS = OSType.Linux;
      } else {
        detectedOS = OSType.Other;
      }
    }
    return detectedOS;
  }
}

Answered by: Dainton189 | Posted: 01-03-2022



Answer 5

The following JavaFX classes have static methods to determine current OS (isWindows(),isLinux()...):

  • com.sun.javafx.PlatformUtil
  • com.sun.media.jfxmediaimpl.HostUtils
  • com.sun.javafx.util.Utils

Example:

if (PlatformUtil.isWindows()){
           ...
}

Answered by: Tess197 | Posted: 01-03-2022



Answer 6

TL;DR

For accessing OS use: System.getProperty("os.name").


But WAIT!!!

Why not create a utility class, make it reusable! And probably much faster on multiple calls. Clean, clear, faster!

Create a Util class for such utility functions. Then create public enums for each operating system type.

public class Util {     
        public enum OS {
            WINDOWS, LINUX, MAC, SOLARIS
        };// Operating systems.

    private static OS os = null;

    public static OS getOS() {
        if (os == null) {
            String operSys = System.getProperty("os.name").toLowerCase();
            if (operSys.contains("win")) {
                os = OS.WINDOWS;
            } else if (operSys.contains("nix") || operSys.contains("nux")
                    || operSys.contains("aix")) {
                os = OS.LINUX;
            } else if (operSys.contains("mac")) {
                os = OS.MAC;
            } else if (operSys.contains("sunos")) {
                os = OS.SOLARIS;
            }
        }
        return os;
    }
}

Now, you can easily invoke class from any class as follows,(P.S. Since we declared os variable as static, it will consume time only once to identify the system type, then it can be used until your application halts. )

            switch (Util.getOS()) {
            case WINDOWS:
                //do windows stuff
                break;
            case LINUX:

and That is it!

Answered by: Ryan305 | Posted: 01-03-2022



Answer 7

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.

Answered by: Rafael767 | Posted: 01-03-2022



Answer 8

Try this,simple and easy

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

Answered by: Sarah859 | Posted: 01-03-2022



Answer 9

If you're interested in how an open source project does stuff like this, you can check out the Terracotta class (Os.java) that handles this junk here:

And you can see a similar class to handle JVM versions (Vm.java and VmVersion.java) here:

Answered by: Sarah682 | Posted: 01-03-2022



Answer 10

I think following can give broader coverage in fewer lines

import org.apache.commons.exec.OS;

if (OS.isFamilyWindows()){
                //load some property
            }
else if (OS.isFamilyUnix()){
                //load some other property
            }

More details here: https://commons.apache.org/proper/commons-exec/apidocs/org/apache/commons/exec/OS.html

Answered by: Rubie115 | Posted: 01-03-2022



Answer 11

Below code shows the values that you can get from System API, these all things you can get through this API.

public class App {
    public static void main( String[] args ) {
        //Operating system name
        System.out.println(System.getProperty("os.name"));

        //Operating system version
        System.out.println(System.getProperty("os.version"));

        //Path separator character used in java.class.path
        System.out.println(System.getProperty("path.separator"));

        //User working directory
        System.out.println(System.getProperty("user.dir"));

        //User home directory
        System.out.println(System.getProperty("user.home"));

        //User account name
        System.out.println(System.getProperty("user.name"));

        //Operating system architecture
        System.out.println(System.getProperty("os.arch"));

        //Sequence used by operating system to separate lines in text files
        System.out.println(System.getProperty("line.separator"));

        System.out.println(System.getProperty("java.version")); //JRE version number

        System.out.println(System.getProperty("java.vendor.url")); //JRE vendor URL

        System.out.println(System.getProperty("java.vendor")); //JRE vendor name

        System.out.println(System.getProperty("java.home")); //Installation directory for Java Runtime Environment (JRE)

        System.out.println(System.getProperty("java.class.path"));

        System.out.println(System.getProperty("file.separator"));
    }
}

Answers:-

Windows 7
6.1
;
C:\Users\user\Documents\workspace-eclipse\JavaExample
C:\Users\user
user
amd64


1.7.0_71
http://java.oracle.com/
Oracle Corporation
C:\Program Files\Java\jre7
C:\Users\user\Documents\workspace-Eclipse\JavaExample\target\classes
\

Answered by: Audrey257 | Posted: 01-03-2022



Answer 12

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.). A possible way to avoid tampering with the application parameters is by querying the RuntimeMXBean as shown here. The following code snippet should provide some insight into how this may be achieved.

RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
List<String> arguments = runtimeMxBean.getInputArguments();

for (String argument : arguments) {
    if (argument.startsWith("-Dos.name") {
        // System.getProperty("os.name") altered
    } else if (argument.startsWith("-Dos.arch") {
        // System.getProperty("os.arch") altered
    }
}

Answered by: Miller948 | Posted: 01-03-2022



Answer 13

I find that the OS Utils from Swingx does the job.

Answered by: Catherine438 | Posted: 01-03-2022



Answer 14

String osName = System.getProperty("os.name");
System.out.println("Operating system " + osName);

Answered by: Roman572 | Posted: 01-03-2022



Answer 15

A bit shorter, cleaner (and eagerly computed) version of the top answers:

switch(OSType.DETECTED){
...
}

The helper enum:

public enum OSType {
    Windows, MacOS, Linux, Other;
    public static final  OSType DETECTED;
    static{
        String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
        if ((OS.contains("mac")) || (OS.contains("darwin"))) {
            DETECTED = OSType.MacOS;
        } else if (OS.contains("win")) {
            DETECTED = OSType.Windows;
        } else if (OS.contains("nux")) {
            DETECTED = OSType.Linux;
        } else {
            DETECTED = OSType.Other;
        }
    }
}

Answered by: Alberta876 | Posted: 01-03-2022



Answer 16

I liked Wolfgang's answer, just because I believe things like that should be consts...

so I've rephrased it a bit for myself, and thought to share it :)

/**
 * types of Operating Systems
 *
 * please keep the note below as a pseudo-license
 *
 * helper class to check the operating system this Java VM runs in
 * http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java
 * compare to http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/Os.java
 * http://www.docjar.com/html/api/org/apache/commons/lang/SystemUtils.java.html
 */
public enum OSType {
    MacOS("mac", "darwin"),
    Windows("win"),
    Linux("nux"),
    Other("generic");

    private static OSType detectedOS;

    private final String[] keys;

    private OSType(String... keys) {
        this.keys = keys;
    }

    private boolean match(String osKey) {
        for (int i = 0; i < keys.length; i++) {
            if (osKey.indexOf(keys[i]) != -1)
                return true;
        }
        return false;
    }

    public static OSType getOS_Type() {
        if (detectedOS == null)
            detectedOS = getOperatingSystemType(System.getProperty("os.name", Other.keys[0]).toLowerCase());
        return detectedOS;
    }

    private static OSType getOperatingSystemType(String osKey) {
        for (OSType osType : values()) {
            if (osType.match(osKey))
                return osType;
        }
        return Other;
    }
}

Answered by: Roland781 | Posted: 01-03-2022



Answer 17

You can just use sun.awt.OSInfo#getOSType() method

Answered by: Blake979 | Posted: 01-03-2022



Answer 18

This code for displaying all information about the system os type,name , java information and so on.

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Properties pro = System.getProperties();
    for(Object obj : pro.keySet()){
        System.out.println(" System  "+(String)obj+"     :  "+System.getProperty((String)obj));
    }
}

Answered by: Kellan979 | Posted: 01-03-2022



Answer 19

In com.sun.jna.Platform class you can find useful static methods like

Platform.isWindows();
Platform.is64Bit();
Platform.isIntel();
Platform.isARM();

and much more.

If you use Maven just add dependency

<dependency>
 <groupId>net.java.dev.jna</groupId>
 <artifactId>jna</artifactId>
 <version>5.2.0</version>
</dependency>

Otherwise just find jna library jar file (ex. jna-5.2.0.jar) and add it to classpath.

Answered by: Kimberly263 | Posted: 01-03-2022



Answer 20

Just use com.sun.javafx.util.Utils as below.

if ( Utils.isWindows()){
     // LOGIC HERE
}

OR USE

boolean isWindows = OSInfo.getOSType().equals(OSInfo.OSType.WINDOWS);
       if (isWindows){
         // YOUR LOGIC HERE
       }

Answered by: Madaline722 | Posted: 01-03-2022



Answer 21

Since google points "kotlin os name" to this page, here's the Kotlin version of @Memin 's answer:

private var _osType: OsTypes? = null
val osType: OsTypes
    get() {
        if (_osType == null) {
            _osType = with(System.getProperty("os.name").lowercase(Locale.getDefault())) {
                if (contains("win"))
                    OsTypes.WINDOWS
                else if (listOf("nix", "nux", "aix").any { contains(it) })
                    OsTypes.LINUX
                else if (contains("mac"))
                    OsTypes.MAC
                else if (contains("sunos"))
                    OsTypes.SOLARIS
                else
                    OsTypes.OTHER
            }
        }
        return _osType!!
    }

enum class OsTypes {
    WINDOWS, LINUX, MAC, SOLARIS, OTHER
}

Answered by: Edgar178 | Posted: 01-03-2022



Answer 22

For getting OS name, simply use:

Platform.getOS()

Lets say you want to see if platform is linux:

if (Platform.getOS().equals(Platform.OS_LINUX)) {
}

Similarly Platform class have defined constants for others operating system names. Platform class is part of org.eclipse.core.runtime package.

Answered by: Rafael947 | Posted: 01-03-2022



Similar questions

c# - How can I programmatically determine my processor type?

How can I determine programmatically whether my machine is an x86, x64 or an IA64?


jsp - Programmatically Determine Java Session Timeout

Is there any way for a java servlet/jsp to determine the webserver's session timeout (in seconds, minutes, etc...)? I tried looking in the HttpSession and System API, but didn't see any property for determining the webserver's session timeout. I know that this value is set in web.xml, but I am designing a java library which needs to determine this through code. Note: I am designing for a generic webserver and canno...


java - programmatically determine generic type

apologies if this is a duplicate. Is there any way to determine what generic type a class is? ie I want to know what T is.... public void doSomething(SomeClass&lt;T&gt; thing) { Class&lt;T&gt; t = ???; } thanks, p.


java - android determine programmatically if voice dictation on soft keyboard is enabled

I am writing an app that requires a high level of security. The app will be deployed on a Droid X device. I cannot allow the user to access the voice to text feature of the soft keyboard (by touching the microphone icon) because the audio and text cannot be sent over the internet. There is a way to disable this feature in Settings by going to Language &amp; keyboard --> Multi-touch keyboard --> and then uncheck the Voice d...


java - How to programmatically determine all valid XML nodes from a schema

Is there an existing Java library that will let me determine all valid nodes for a point in an XML document (specified by XPath, or otherwise), given an XML schema?


java - how to programmatically determine if android is connected to wifi?

I'm trying to setup a test for automation on a new android app that I'm developing but having a bit of trouble with one of the apis The problem i'm facing is I want to start the test AFTER wifi has a connection, not when its in the connecting state. I have tried two solutions but had no luck and test seems to start before my android device is fully connected (no x on the wifi bars) wifiManager.setWi...


java - How do I determine if USE NETWORK PROVIDED VALUES is checked in android programmatically?

I have searched n googled everything possible related to this but did not quite find anything concrete. How can i determine if the option USE NETWORK PROVIDED VALUES in the date/time settings is checked?


java - Can I programmatically determine if a spring bean is not singleton?

When I get a spring bean (via getBean()), is there any way to verify from java code that the bean has been defined with scope=prototype ? Spring config: &lt;bean class="foo.Bar" scope="prototype" /&gt; Java:sc MyBean bean = springApplicationContext.getBean("MyBean"); I could just instantiate it twice and compare the objects, but I'd like to avoid...


java - Jackson: programmatically determine subtypes

Given an arbitrary Class object, what is the best way to determine the subtypes of that class registered with Jackson? For example, here's a simple case where classes Lion and Penguin are subtypes of Animal: @JsonTypeInfo(use = JsonTypeInfo.Id.NAME) @JsonSubTypes({ @JsonSubTypes.Type(Lion.class), @JsonSubTypes.Type(Penguin.class)}) ...


java - Programmatically determine list of JRE classes that need not be imported

I need to programmatically find out which JRE classes can be referenced in a compilation unit without being imported (for static code analysis). We can disregard package-local classes. According to the JLS, classes from the package java.lang are implicitly imported. The output should be a list of


java - How do I programmatically inspect a HTML document

I have a database full of small HTML documents and I need to programmatically insert several into, say, a PDF document with iText or a Word document with Aspose.Words. I need to preserve any formatting within the HTML documents (within reason, honouring &lt;b&gt; tags is a must, CSS like &lt;span style="blah"&gt; is a nice-to-have). Both iText and Aspose work (roughly) along the lines: ...


java - Programmatically generate an Eclipse project

I use eclipse to work on an application which was originally created independently of eclipse. As such, the application's directory structure is decidedly not eclipse-friendly. I want to programmatically generate a project for the application. The .project and .classpath files are easy enough to figure out, and I've learned that projects are stored in the workspace under &lt;worksp...


eclipse - Can you register an ActiveX dll in Java programmatically?

I have a third-party ActiveX dll, and I'd like to register it programmatically at run time, if possible. Can this be done in Java? The application I'm working with is an Eclipse application on Windows XP.


Convert Word doc to HTML programmatically in Java

I need to convert a Word document into HTML file(s) in Java. The function will take input an word document and the output will be html file(s) based on the number of pages the word document has i.e. if the word document has 3 pages then there will be 3 html files generated having the required page break. I searched for open source/non-commercial APIs which can convert doc to html but for no result. Anybody who have...


java - How can I programmatically test an HTTP connection?

Using Java, how can I test that a URL is contactable, and returns a valid response? http://stackoverflow.com/about


java - How to programmatically add portlet to the JBoss Portal dashboard

Closed. This question does not meet Stack Overflow guid...


java - Programmatically marking an Oracle BPEL task complete

I am using Oracle BPEL Process manager and have a task assigned to a group of users. I try to mark it approved using Java class oracle.bpel.services.workflow.task.ITaskService.updateTaskOutcome(). This works if the task is assigned to an individual user, but if the task is assigned to a group of users, I get an error message about the task not being acquired. If I acquire the task using oracle.bpel.services.workf...


java - How to Send Encrypted Emails Programmatically (from an automated process)

I have a process that runs on a UNIX (Solaris) server that runs nightly and needs to be able to send out encrypted emails. I only need the "encryption" portion, NOT the digital signature / self-repudiation part of PKI. I use MS Outlook in a corporate setting and I am assuming that when a user clicks "Publish to GAL..." under Tools -> Options -> Security, this will publish their PUBLIC KEY to the Global Addr...


java - Need a way to check status of Windows service programmatically

Here is the situation: I have been called upon to work with InstallAnywhere 8, a Java-based installer IDE, of sorts, that allows starting and stopping of windows services, but has no built-in method to query their states. Fortunately, it allows you to create custom actions in Java which can be called at any time during the installation process (by way of what I consider to be a rather convoluted API). I ...


java - Programmatically transcode MPEG-2 videos

I need to be able to programmatically transcode mpeg-2 files to .mp4, .mp3, .wmv, .rm (optional), and .flv (optional), and hopefully generate a thumbnail as well. I found the Java Media Framework, but it frankly looks pretty crappy. This will be running a Linux server, so I could shell out to ffmpeg using Commons Exec - does ffmpeg do everything I need to do? FFmpeg seems pretty daunting, which is why I'm having trouble fi...






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top