Created
July 14, 2019 11:17
-
-
Save sanyarnd/cebb3882ba39449f53ba2a2810e21350 to your computer and use it in GitHub Desktop.
Detect OS on JVM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.nio.file.FileSystem; | |
| import java.nio.file.FileSystems; | |
| import java.util.Locale; | |
| import org.checkerframework.checker.nullness.qual.NonNull; | |
| /** | |
| * Operating systems enumeration. | |
| * | |
| * @author Alexander Biryukov | |
| */ | |
| public enum Os { | |
| /** | |
| * Microsoft Windows operating system. | |
| */ | |
| WINDOWS, | |
| /** | |
| * Linux-based operating system. | |
| */ | |
| LINUX, | |
| /** | |
| * Apple Macintosh operating system. | |
| */ | |
| MAC, | |
| /** | |
| * Other operating systems, also used if {@code os.name} property is not defined. | |
| */ | |
| UNKNOWN; | |
| /** | |
| * Current OS. | |
| * | |
| * @return current OS. | |
| */ | |
| @NonNull | |
| public static Os current() { | |
| final String name = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); | |
| final Os win = name.contains("win") ? WINDOWS : UNKNOWN; | |
| final Os nonLinux = name.contains("mac") ? MAC : win; | |
| return name.contains("linux") ? LINUX : nonLinux; | |
| } | |
| /** | |
| * Check if current OS is Windows. | |
| * | |
| * @return true, if OS is Windows, otherwise false. | |
| */ | |
| public static boolean isWindows() { return Os.current() == Os.WINDOWS; } | |
| /** | |
| * Check if current OS is Linux. | |
| * | |
| * @return true, if OS is Linux, otherwise false. | |
| */ | |
| public static boolean isLinux() { return Os.current() == Os.LINUX; } | |
| /** | |
| * Check if current OS is Mac. | |
| * | |
| * @return true, if OS is Mac, otherwise false. | |
| */ | |
| public static boolean isMac() { return Os.current() == Os.MAC; } | |
| /** | |
| * Check if current OS is unknown. | |
| * | |
| * @return true, if OS is unknown, otherwise false. | |
| */ | |
| public static boolean isUnknown() { return Os.current() == Os.UNKNOWN; } | |
| /** | |
| * Check if current OS is POSIX-compliant. | |
| * | |
| * @return true, if OS is POSIX-compliant, false otherwise. | |
| */ | |
| public static boolean isPosix() { | |
| FileSystem fileSystem = FileSystems.getDefault(); | |
| if (fileSystem == null) { | |
| return false; | |
| } | |
| return fileSystem.supportedFileAttributeViews().contains("posix"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment