1

I have a Java Application which uses xml file to load settings during s start time. I want to run this application on Linux, Windows and many other Operating systems.

The problem is the file path which is different in every OS. The only solution that I think on is to get the OS platform type and based on it to load the appropriate config file:

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

Is there any better approach?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • 1
    Why can't you use File.separator? Or do you mean the files are on completely different paths? – Chandranshu Nov 20 '13 at 09:03
  • Can you give me some basic example please? – Peter Penzov Nov 20 '13 at 09:15
  • 1
    Say, if the file is always in your classpath at a relative path of `/some/deep/folder/myFile.xml`. Then, you can replace the forward slashes with `File.separator`. On the other hand, if you are dependent on absolute paths, you have a much serious problem. For linux, the file can be /home/current_user/.prefs/myFile.xml, for windows, it'll be `C:\Users\Current User\Application Data\myFile.xml`. Reconciling the absolute paths will be much more difficult. – Chandranshu Nov 20 '13 at 09:18
  • See this answer: http://stackoverflow.com/questions/1464291/how-to-really-read-text-file-from-classpath-in-java – Chandranshu Nov 20 '13 at 09:19
  • Doesn't windows also accept forward slashes in path names? Not sure about Mac, but I thought it does too. – mdriesen Nov 20 '13 at 19:00

1 Answers1

1

Windows accept forward slash in paths but the best solution is to use the File.separator property to get the separator.

milonimrod
  • 306
  • 2
  • 3