如何获取配置文件的操作系统

时间:2013-11-20 08:56:32

标签: java

我有一个Java应用程序,它使用xml文件在开始时加载设置。 我想在Linux,Windows和许多其他操作系统上运行此应用程序。

问题是每个操作系统中的文件路径不同。我认为唯一的解决方案是获取OS平台类型并基于它来加载适当的配置文件:

/**
 * helper class to check the operating system this Java VM runs in
 */
public static final class OsCheck {
  /**
   * types of Operating Systems
   */
  public enum OSType {
    Windows, MacOS, Linux, Other
  };

  protected static OSType detectedOS;

  /**
   * detected 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();
      if (OS.indexOf("win") >= 0) {
        detectedOS = OSType.Windows;
      } else if ((OS.indexOf("mac") >= 0) || (OS.indexOf("darwin") >= 0)) {
        detectedOS = OSType.MacOS;
      } else if (OS.indexOf("nux") >= 0) {
        detectedOS = OSType.Linux;
      } else {
        detectedOS = OSType.Other;
      }
    }
    return detectedOS;
  }
}

有没有更好的方法?

1 个答案:

答案 0 :(得分:1)

Windows接受路径中的正斜杠,但最好的解决方案是使用 File.separator属性来获取分隔符。