Home » Java » How do I programmatically determine operating system in Java?

How do I programmatically determine operating system in Java?

Posted by: admin November 2, 2017 Leave a comment

Questions:

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?

Answers:

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. 🙂

Questions:
Answers:

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.

Questions:
Answers:

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?

Questions:
Answers:
System.getProperty("os.name")

Questions:
Answers:

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;
  }
}

Questions:
Answers:

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()){
           ...
}

Questions:
Answers:

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:

Questions:
Answers:
    private static String OS = System.getProperty("os.name").toLowerCase();

    public static void detectOS() {
        if (isWindows()) {

        } else if (isMac()) {

        } else if (isUnix()) {

        } else {

        }
    }

    private static boolean isWindows() {
        return (OS.indexOf("win") >= 0);
    }

    private static boolean isMac() {
        return (OS.indexOf("mac") >= 0);
    }

    private static boolean isUnix() {
        return (OS.indexOf("nux") >= 0);
    }

Questions:
Answers:

Let’s say you have 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;
    }
}

Then you can easly invoke class from any class as follows,(P.S. Since the 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 so on…

Questions:
Answers:

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

Questions:
Answers:

Taken from this project https://github.com/RishiGupta12/serial-communication-manager

String osName = System.getProperty("os.name");
String osNameMatch = osName.toLowerCase();
if(osNameMatch.contains("linux")) {
    osType = OS_LINUX;
}else if(osNameMatch.contains("windows")) {
    osType = OS_WINDOWS;
}else if(osNameMatch.contains("solaris") || osNameMatch.contains("sunos")) {
    osType = OS_SOLARIS;
}else if(osNameMatch.contains("mac os") || osNameMatch.contains("macos") || osNameMatch.contains("darwin")) {
    osType = OS_MAC_OS_X;
}else {
}

Questions:
Answers:

Try this,simple and easy

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

Questions:
Answers:

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
\

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

Questions:
Answers:

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;
    }
}

Questions:
Answers:

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));
    }
}

Questions:
Answers:

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

Questions:
Answers:

You can get the OS type name by using

System.out.println(System.getProperty("os.name"));

You can get all the info related to OS by:

public class MyFirstJavaProgram {

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

It will output very much details

— listing properties —

java.runtime.name=OpenJDK Runtime Environment

sun.boot.library.path=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0…

java.vm.version=25.65-b01

java.vm.vendor=Oracle Corporation

java.vendor.url=http://java.oracle.com/

path.separator=:

java.vm.name=OpenJDK 64-Bit Server VM

file.encoding.pkg=sun.io

user.country=US

sun.java.launcher=SUN_STANDARD

sun.os.patch.level=unknown

java.vm.specification.name=Java Virtual Machine Specification

user.dir=/web/com/1502258867_87863

java.runtime.version=1.8.0_65-b17

java.awt.graphicsenv=sun.awt.X11GraphicsEnvironment

java.endorsed.dirs=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0…

os.arch=amd64

java.io.tmpdir=/tmp

line.separator=

java.vm.specification.vendor=Oracle Corporation

os.name=Linux

sun.jnu.encoding=UTF-8

java.library.path=/home/cg/root/GNUstep/Library/Librari…

java.specification.name=Java Platform API Specification

java.class.version=52.0

sun.management.compiler=HotSpot 64-Bit Tiered Compilers

os.version=3.10.0-327.4.4.el7.x86_64

user.home=/usr/share/httpd

user.timezone=

java.awt.printerjob=sun.print.PSPrinterJob

file.encoding=UTF-8

java.specification.version=1.8

user.name=apache

java.class.path=/home/cg/root/GNUstep/Library/Librari…

java.vm.specification.version=1.8

sun.arch.data.model=64

java.home=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0…

sun.java.command=MyFirstJavaProgram

java.specification.vendor=Oracle Corporation

user.language=en

awt.toolkit=sun.awt.X11.XToolkit

java.vm.info=mixed mode

java.version=1.8.0_65

java.ext.dirs=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0…

sun.boot.class.path=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0…

java.vendor=Oracle Corporation

file.separator=/

java.vendor.url.bug=http://bugreport.sun.com/bugreport/

sun.cpu.endian=little

sun.io.unicode.encoding=UnicodeLittle

sun.cpu.isalist=