Frage

Ich mag das Betriebssystem des Hosts bestimmen, dass mein Java-Programm programmatisch ausgeführt wird (zum Beispiel: Ich möchte in der Lage sein, verschiedene Eigenschaften zu laden, basierend auf, ob ich auf einer Windows- oder Unix-Plattform). Was ist der sicherste Weg, dies mit 100% Zuverlässigkeit zu tun?

War es hilfreich?

Lösung

Sie können mit:

System.getProperty("os.name")

P. S. Sie können diesen Code nützlich finden:

class ShowProperties {
    public static void main(String[] args) {
        System.getProperties().list(System.out);
    }
}

Alles, was sie tut, ist, die alle Eigenschaften von Java-Implementierungen zur Verfügung gestellt ausdrucken. Es wird Ihnen eine Vorstellung von dem, was Sie über Ihre Java-Umgebung über Eigenschaften herausfinden können. : -)

Andere Tipps

Wie in anderen Antworten erwähnt, stellt System.getProperty die Rohdaten. Doch die Apache Commons Lang Komponente eine Wrapper für java.lang.System mit praktischen Eigenschaften wie < a href = "http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/SystemUtils.html#IS_OS_WINDOWS" rel = "nofollow noreferrer"> SystemUtils.IS_OS_WINDOWS , ähnlich wie die oben genannten SwingX OS util.

Oktober 2008:

Ich würde empfehlen, es in einer statischen Variablen zwischenzuspeichern:

public static final class OsUtils
{
   private static String OS = null;
   public static String getOsName()
   {
      if(OS == null) { OS = System.getProperty("os.name"); }
      return OS;
   }
   public static boolean isWindows()
   {
      return getOsName().startsWith("Windows");
   }

   public static boolean isUnix() // and so on
}

Auf diese Weise jedes Mal, wenn Sie für die Os fragen, Sie holen nicht das Eigentum mehr als einmal in der Lebensdauer der Anwendung.


Februar 2016: 7+ Jahre später:

Es ist ein Fehler bei Windows 10 (die nicht zum Zeitpunkt der ursprünglichen Antwort existierten).
Siehe " Java‚os.name‘für Windows 10? "

einige der Links in den Antworten scheinen oben gebrochen zu sein. Ich habe in dem unten stehenden Code Zeiger auf aktuelle Quellcode hinzugefügt und einen Ansatz biete für die Prüfung mit einer Enum als Antwort Handhabung, so dass eine switch-Anweisung verwendet werden kann, wenn das Ergebnis der Bewertung:

OsCheck.OSType ostype=OsCheck.getOperatingSystemType();
switch (ostype) {
    case Windows: break;
    case MacOS: break;
    case Linux: break;
    case Other: break;
}

Die Hilfsklasse ist:

/**
 * helper class to check the operating system this Java VM runs in
 *
 * please keep the notes below as a pseudo-license
 *
 * http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java
 * compare to http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/Os.java
 * http://www.docjar.com/html/api/org/apache/commons/lang/SystemUtils.java.html
 */
import java.util.Locale;
public static final class OsCheck {
  /**
   * types of Operating Systems
   */
  public enum OSType {
    Windows, MacOS, Linux, Other
  };

  // cached result of OS detection
  protected static OSType detectedOS;

  /**
   * detect the operating system from the os.name System property and cache
   * the result
   * 
   * @returns - the operating system detected
   */
  public static OSType getOperatingSystemType() {
    if (detectedOS == null) {
      String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
      if ((OS.indexOf("mac") >= 0) || (OS.indexOf("darwin") >= 0)) {
        detectedOS = OSType.MacOS;
      } else if (OS.indexOf("win") >= 0) {
        detectedOS = OSType.Windows;
      } else if (OS.indexOf("nux") >= 0) {
        detectedOS = OSType.Linux;
      } else {
        detectedOS = OSType.Other;
      }
    }
    return detectedOS;
  }
}

Die folgenden JavaFX Klassen haben statische Methoden aktuelle OS (isWindows (), isLinux () ...) zu bestimmen:

  • com.sun.javafx.PlatformUtil
  • com.sun.media.jfxmediaimpl.HostUtils
  • com.sun.javafx.util.Utils

Beispiel:

if (PlatformUtil.isWindows()){
           ...
}
    private static String OS = System.getProperty("os.name").toLowerCase();

    public static void detectOS() {
        if (isWindows()) {

        } else if (isMac()) {

        } else if (isUnix()) {

        } else {

        }
    }

    private static boolean isWindows() {
        return (OS.indexOf("win") >= 0);
    }

    private static boolean isMac() {
        return (OS.indexOf("mac") >= 0);
    }

    private static boolean isUnix() {
        return (OS.indexOf("nux") >= 0);
    }

Wenn Sie daran interessiert, wie ein Open-Source-Projekt macht Sachen wie diese, können Sie die Terrakotta-Klasse Check-out (Os.java), die diesen Müll hier behandelt:

Und Sie können eine ähnliche Klasse siehe JVM-Versionen (Vm.java und VmVersion.java) zu handhaben hier:

von diesem Projekt Taken https://github.com/RishiGupta12/serial-communication-manager

String osName = System.getProperty("os.name");
String osNameMatch = osName.toLowerCase();
if(osNameMatch.contains("linux")) {
    osType = OS_LINUX;
}else if(osNameMatch.contains("windows")) {
    osType = OS_WINDOWS;
}else if(osNameMatch.contains("solaris") || osNameMatch.contains("sunos")) {
    osType = OS_SOLARIS;
}else if(osNameMatch.contains("mac os") || osNameMatch.contains("macos") || osNameMatch.contains("darwin")) {
    osType = OS_MAC_OS_X;
}else {
}

Angenommen, Sie haben eine Util Klasse für solche Nutzenfunktionen haben. Dann erstellen Sie öffentliche Aufzählungen für jeden Betriebssystem-Typen.

public class Util {     
        public enum OS {
            WINDOWS, LINUX, MAC, SOLARIS
        };// Operating systems.

    private static OS os = null;

    public static OS getOS() {
        if (os == null) {
            String operSys = System.getProperty("os.name").toLowerCase();
            if (operSys.contains("win")) {
                os = OS.WINDOWS;
            } else if (operSys.contains("nix") || operSys.contains("nux")
                    || operSys.contains("aix")) {
                os = OS.LINUX;
            } else if (operSys.contains("mac")) {
                os = OS.MAC;
            } else if (operSys.contains("sunos")) {
                os = OS.SOLARIS;
            }
        }
        return os;
    }
}

Dann können Sie easly Klasse von jeder Klasse wie folgt aufrufen, (PS Da die wir os Variable als statisch deklariert, wird es Zeit verbrauchen nur einmal den Systemtyp zu identifizieren, dann kann es, bis Ihre Anwendung stoppt verwendet werden.)

            switch (Util.getOS()) {
            case WINDOWS:
                //do windows stuff
                break;
            case LINUX:

und so weiter ...

Ich finde, dass die OS Utils von SwingX die Arbeit erledigt.

Versuchen Sie dieses, einfach und leicht

System.getProperty("os.name");
System.getProperty("os.version");
System.getProperty("os.arch");

Im Folgenden Code die Werte zeigt, die Sie von System API zu bekommen, diese alle Dinge, die Sie über diese API erhalten.

public class App {
    public static void main( String[] args ) {
        //Operating system name
        System.out.println(System.getProperty("os.name"));

        //Operating system version
        System.out.println(System.getProperty("os.version"));

        //Path separator character used in java.class.path
        System.out.println(System.getProperty("path.separator"));

        //User working directory
        System.out.println(System.getProperty("user.dir"));

        //User home directory
        System.out.println(System.getProperty("user.home"));

        //User account name
        System.out.println(System.getProperty("user.name"));

        //Operating system architecture
        System.out.println(System.getProperty("os.arch"));

        //Sequence used by operating system to separate lines in text files
        System.out.println(System.getProperty("line.separator"));

        System.out.println(System.getProperty("java.version")); //JRE version number

        System.out.println(System.getProperty("java.vendor.url")); //JRE vendor URL

        System.out.println(System.getProperty("java.vendor")); //JRE vendor name

        System.out.println(System.getProperty("java.home")); //Installation directory for Java Runtime Environment (JRE)

        System.out.println(System.getProperty("java.class.path"));

        System.out.println(System.getProperty("file.separator"));
    }
}

Antworten: -

Windows 7
6.1
;
C:\Users\user\Documents\workspace-eclipse\JavaExample
C:\Users\user
user
amd64


1.7.0_71
http://java.oracle.com/
Oracle Corporation
C:\Program Files\Java\jre7
C:\Users\user\Documents\workspace-Eclipse\JavaExample\target\classes
\

Ich denke, kann sie breitere Abdeckung in weniger Zeilen geben

import org.apache.commons.exec.OS;

if (OS.isFamilyWindows()){
                //load some property
            }
else if (OS.isFamilyUnix()){
                //load some other property
            }

Weitere Informationen finden Sie hier: https: //commons.apache.org/proper/commons-exec/apidocs/org/apache/commons/exec/OS.html

String osName = System.getProperty("os.name");
System.out.println("Operating system " + osName);

Ich mochte Wolfgang Antwort, nur weil ich glaube, die Dinge so sein sollte consts ...

, also habe ich es ein bisschen für mich neu formuliert, und dachte, es zu teilen:)

/**
 * types of Operating Systems
 *
 * please keep the note below as a pseudo-license
 *
 * helper class to check the operating system this Java VM runs in
 * http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java
 * compare to http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/Os.java
 * http://www.docjar.com/html/api/org/apache/commons/lang/SystemUtils.java.html
 */
public enum OSType {
    MacOS("mac", "darwin"),
    Windows("win"),
    Linux("nux"),
    Other("generic");

    private static OSType detectedOS;

    private final String[] keys;

    private OSType(String... keys) {
        this.keys = keys;
    }

    private boolean match(String osKey) {
        for (int i = 0; i < keys.length; i++) {
            if (osKey.indexOf(keys[i]) != -1)
                return true;
        }
        return false;
    }

    public static OSType getOS_Type() {
        if (detectedOS == null)
            detectedOS = getOperatingSystemType(System.getProperty("os.name", Other.keys[0]).toLowerCase());
        return detectedOS;
    }

    private static OSType getOperatingSystemType(String osKey) {
        for (OSType osType : values()) {
            if (osType.match(osKey))
                return osType;
        }
        return Other;
    }
}

Sie können nur sun.awt.OSInfo # getOSType () Methode

verwenden

Dieser Code für die Anzeige aller Informationen über das System o Typen, Namen, Java-Informationen und so weiter.

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Properties pro = System.getProperties();
    for(Object obj : pro.keySet()){
        System.out.println(" System  "+(String)obj+"     :  "+System.getProperty((String)obj));
    }
}

In com.sun.jna.Platform Klasse können Sie nützliche statische Methoden wie

finden
Platform.isWindows();
Platform.is64Bit();
Platform.isIntel();
Platform.isARM();

und vieles mehr.

Wenn Sie Maven verwenden nur die Abhängigkeit hinzufügen

<dependency>
 <groupId>net.java.dev.jna</groupId>
 <artifactId>jna</artifactId>
 <version>5.2.0</version>
</dependency>

Ansonsten nur jna Bibliothek jar-Datei (ex. Jna-5.2.0.jar) und fügen Sie Classpath.

Wie unten verwenden com.sun.javafx.util.Utils.

if ( Utils.isWindows()){
     // LOGIC HERE
}

OR USE

boolean isWindows = OSInfo.getOSType().equals(OSInfo.OSType.WINDOWS);
       if (isWindows){
         // YOUR LOGIC HERE
       }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top