1

I had been through this query but did not get proper answer.

I have conf.txt in Windows folder c:\winapp\Game\core\conf.txt

I have conf.txt in Linux folder /usr/Game/core/conf.txt

So, I know the relative path that starts from Game folder

Without using OS specific code like System.getProperty(""), Do we have an approach to write a portable Java program?

Community
  • 1
  • 1
overexchange
  • 15,768
  • 30
  • 152
  • 347

2 Answers2

0

The short answer is no.

I haven't used Windows regularly in a number of years, so I don't know if "c:\winapp" is a 'standard' directory, but there is nothing in Java libraries that would automagically associate c:\winapp on Windows with /usr on Linux.

So, you'd either have to detect the OS at runtime, and use the appropriate path (hard-coded into your application) or go with System.getProperty(), and have the user set the system property.

A slightly better approach might be to put the configuration file in the user's home directory. Then, you could do System.getProperty("user.home"), and the user wouldn't have to set anything.

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67
0

Short answer: yes.

I expect you know, how your application is packed. E.g.

/core/conf.txt
/lib/*.jar
/bin/*.(sh|cmd|exe)

In this case you can use

public static void main(String[] args) throws Exception {
    String home = System.getenv("GAME_HOME"); // For dev environment.
    File appHome;

    if (home == null) {
        File libs = new File(Test.class.getProtectionDomain().getCodeSource().getLocation().toURI());
        appHome = new File(libs, "..");
    }
    else {
        appHome = new File(home);
    }

    appHome = appHome.getCanonicalFile();
    System.out.println("App home directory: " + appHome);
}

Of course Test class should be placed in one of the lib/*.jar files.

ursa
  • 4,404
  • 1
  • 24
  • 38