Languages

Java check if linux is current operating system / detect os

4 points
Asked by:
Kate_C
2872

How can I detect if I run my java application on Linux operating system?

I want to ensure I am on Linux before I try to read the file from Linux path:

/root/test_file.txt

 

1 answers
4 points
Answered by:
Kate_C
2872

Simples way to check if we are on Linux operating system: 

public static boolean isLinux() {
    String OS = System.getProperty("os.name");
    return (OS.contains("nix") || OS.contains("nux") || OS.contains("aix"));
}

If we are on Linux or Unix operating system this method will return true, otherwise it will return fasle.

Simple util to check if above mehtod works:

public class SystemUtil {

    public static void main(String[] args) {

        // if we run this util on Linux eg Ubuntu, Debian, CentOS
        System.out.println(isLinux()); // true
    }

    public static boolean isLinux() {
        String OS = System.getProperty("os.name");
        return (OS.contains("nix") || OS.contains("nux") || OS.contains("aix"));
    }

    public static boolean isWindows() {
        String OS = System.getProperty("os.name");
        return OS.toLowerCase().contains("win");
    }
}

Output:

true

This example was executed on Ubuntu.

0 comments Add comment
Hey ūüĎč
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.