Languages

Java check if linux is current operating system / detect os

4 points
Asked by:
Kate_C
19800

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 answer
4 points
Answered by:
Kate_C
19800

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
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join