Skip to content

Instantly share code, notes, and snippets.

@sanyarnd
Created July 14, 2019 11:17
Show Gist options
  • Select an option

  • Save sanyarnd/cebb3882ba39449f53ba2a2810e21350 to your computer and use it in GitHub Desktop.

Select an option

Save sanyarnd/cebb3882ba39449f53ba2a2810e21350 to your computer and use it in GitHub Desktop.
Detect OS on JVM
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