How to detect OS in java

In this post, we will see how to detect OS which you are using. You can use System.getProperty("os.name") to get current OS name. Sometimes , we need to write logic based on OS, so we get use this logic to detect current OS.

Java Program:

package org.arpit.java2blog;

/*
 * @Author Arpit Mandliya
 */
public class getHomeDirectoryMain {

	public static void main(String[] args)
	{
	
		String osName="";
		// Getting OS name
		osName = System.getProperty("os.name");
	
		System.out.println("--------------");
		
		System.out.println(osName);
		
		if (osName.toLowerCase().indexOf("win") >= 0) {
			System.out.println("You are using Windows");
		} else if (osName.toLowerCase().indexOf("mac") >= 0) {
			System.out.println("You are using MAC");
		} else if (osName.toLowerCase().indexOf("nix") >= 0 || osName.toLowerCase().indexOf("nux") >= 0 || osName.toLowerCase().indexOf("aix") > 0 ) {
			System.out.println("You are using Unix or Linux");
		} else if (osName.toLowerCase().indexOf("sunos") >= 0) {
			System.out.println("You are using Solaris");
		} else {
			System.out.println("Not able to detect OS");
		}
		
		System.out.println("--------------");
	}
}

I am using Mac os to run above program. When I ran above program, I got below output
--------------
Mac OS X
You are using MAC
--------------



Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012