Friday 12 May 2017

How to detect Operating System in Java?

In this post, I am going to explain how to detect operating system in Java.

By using the statement ‘System.getProperty("os.name");’, you can detect the operating system.

String osName = System.getProperty("os.name");

Find the following working application.

OperatingSystem.java
package com.sample;

public enum OperatingSystem {
 WINDOWS, LINUX, MAC_OS, SOLARIS, OTHER
}

OperatingSystemUtil.java
package com.sample;

public class OperatingSystemUtil {
 
 /**
  * 
  * @return the operating system that you are currently working on
  */
 public static OperatingSystem getCurrentPlattform() {
  String osName = System.getProperty("os.name");

  if (osName.toLowerCase().contains("windows")) {
   return OperatingSystem.WINDOWS;
  }
  if (osName.toLowerCase().contains("linux")) {
   return OperatingSystem.LINUX;
  }
  if (osName.startsWith("Mac OS")) {
   return OperatingSystem.MAC_OS;
  }
  if (osName.startsWith("SunOS")) {
   return OperatingSystem.SOLARIS;
  }

  return OperatingSystem.OTHER;
 }

}


OperatingSystemUtilTest.java
package com.sample;

public class OperatingSystemUtilTest {
 public static void main(String args[]){
  OperatingSystem os = OperatingSystemUtil.getCurrentPlattform();
  System.out.println(os);
 }
}




No comments:

Post a Comment