How to detect operating system in Java

Detect operating system in javaIn the following article, there is a short Java snippet that can be used to read the operating system of the computer running the Java program.

In addition, it is the first Java snippet at all here in the blog. Although I have been writing a few lines of Java code again and again for a couple of years, I really couldn’t befriend myself (especially with regard to my C # passion) with Java so far yet. But since I have to deal more and more with Java on the job, however, this will soon be reflected in the blog. But let’s come to the Snippet now…

Read operating system in Java

In order to identify the computer’s operating system in Java, the getProperty-method of the system-class is suitable. Using this method, the name of the operating system can be read out using the “os.name” parameter. By using if-else in combination with the check for certain text elements, a distinction can be made between the various operating systems now.

String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")){
    //Operating system is based on Windows
}
else if (os.contains("osx")){
    //Operating system is Apple OSX based
}	    
else if (os.contains("nix") || os.contains("aix") || os.contains("nux")){
    //Operating system is based on Linux/Unix/*AIX
}

As always – feedback, criticism and suggestions for improvement are welcome in the comments!

0 Comments

Leave a comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked