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

Java 如何获取配置文件的操作系统,java,Java,我有一个Java应用程序,它使用xml文件在启动时加载设置。 我想在Linux、Windows和许多其他操作系统上运行这个应用程序 问题是每个操作系统中的文件路径都不同。我认为唯一的解决方案是获取操作系统平台类型并基于它加载相应的配置文件: /** * helper class to check the operating system this Java VM runs in */ public static final class OsCheck { /** * types o

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

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

/**
 * 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;
  }
}

有更好的方法吗?

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

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

为什么不能使用File.separator?或者你的意思是文件位于完全不同的路径上?你能给我一些基本的例子吗?比如,如果文件总是在类路径中的相对路径为
/some/deep/folder/myFile.xml
。然后,可以用
File.separator
替换正斜杠。另一方面,如果你依赖于绝对路径,你会有一个非常严重的问题。对于linux,文件可以是/home/current\u user/.prefs/myFile.xml;对于windows,文件可以是
C:\Users\current user\Application Data\myFile.xml
。协调绝对路径要困难得多。请看下面的答案:windows不也接受路径名中的正斜杠吗?我对Mac不太清楚,但我认为它也是。为什么不能使用File.separator?或者你的意思是文件位于完全不同的路径上?你能给我一些基本的例子吗?比如,如果文件总是在类路径中的相对路径为
/some/deep/folder/myFile.xml
。然后,可以用
File.separator
替换正斜杠。另一方面,如果你依赖于绝对路径,你会有一个非常严重的问题。对于linux,文件可以是/home/current\u user/.prefs/myFile.xml;对于windows,文件可以是
C:\Users\current user\Application Data\myFile.xml
。协调绝对路径要困难得多。请看下面的答案:windows不也接受路径名中的正斜杠吗?我不太清楚Mac,但我认为它也是。