How to Detect the OS – Operating System in Java

0 Flares 0 Flares ×

I was developing a Java application to run on any platform but depending on the OS, the program needs to do some tasks differently. So then I started exploring how can the Java program detect the operating system. So here I have come up with a handy class that can detect the OS under which it is running.

Note: Here I am going to use System.getProperty(“os.name”) to find the OS name.

package com.lessonslab.core;

public class OSDetector
{
public static void main(String args[])
{
//Get the OS name from the System property
String osName = System.getProperty("os.name");
getOS(osName);
}

/**
*
* @param osName
*/

private static void getOS(String osName)
{
if(osName != null)
{
osName = osName.toLowerCase();
if(osName.contains("win"))
{
System.out.println("You are using Windows system");
}
else if(osName.contains("mac"))
{
System.out.println("You are using Macintosh");
}
else if(osName.contains("lin"))
{
System.out.println("You are using Linux");
}
else if(osName.contains("sol") || osName.contains("sun"))
{
System.out.println("You are using Sun Solaris");
}
else if(osName.contains("sol") || osName.contains("sun"))
{
System.out.println("You are using Sun Solaris");
}
else if(osName.contains("free"))
{
System.out.println("You are using Sun FreeBSD");
}
else if(osName.contains("nix") || osName.contains("aix"))
{
System.out.println("You are using Unix");
}
else
{
System.out.println("Your OS is not recognized");
}
}
else
{
System.out.println("No OS Found");
}
}
}

The above program is capable of detecting Unix, MAC OS, Linux, SUN Solaris, Windows. If any other OS is found it will output as “Your OS is not recognized”.

Guru

+Ayodhyanath Guru holds a B.Tech degree in Electrical Engineering and has worked with various prestigious clients in the IT industry and presently working as a Software Engineer. He is a part time blogger and presently authors the Jafaloo.Com blog. Being a tech enthusiast Guru likes to surf the web and blogs about interesting technical topics like How-To guides, freewares, Tutorials, Software, Gadgets, web applications etc. Apart from blogging he likes coding in Java/J2EE and PHP.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 0 Flares ×