0

I am making an java application which reads a file from a particular location. The location of the file is in the folder retrived from

getCanonicalPath(). 

The problem i am facing is that when i am running my application in Eclipse the canonical path is different from the one which Dr Java sees. So, what should i do before delivering my application to the client to make sure that it sees the file no matter which ide/command prompt is used to run the application. Obviously it would not be a good idea to copy the same file across all possible folders to cover different possibilities of getCanonicalPath.

Thanks

mu_sa
  • 2,685
  • 10
  • 39
  • 58

3 Answers3

1

One of the solution is to have this file in your classpath and load it from your classpath, with a code like

URL url = getClass().getClassLoader().getResource(path);
        if(url != null) {
            try {
                return new File(url.toURI().getPath());
            } catch (URISyntaxException e) {
                return null;
            }
        }

This is standard if this file is a configuration file. Usually in a standard java project layout you put this in the folder src/main/resources.

If this is more of a data file, you should put in a configuration file its path, and have different configurations, one for your station and one for production on the client machine. Of course in this case the configuration file is in the class path ;).

jolivier
  • 7,380
  • 3
  • 29
  • 47
0

A common solution is to place the file in a directory which is in the class path. If you use getResource or getResourceAsInputStream you can find the file regardless of where it is provided its in the class path. if you use maven you can be sure how the classpath is setup regardless of the IDE used.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

You should always load file ClassLoader using API like Test.class.getClassLoader().getResource(name),Test.class.getClassLoader().getResourceAsStream(name) More Information available here

Community
  • 1
  • 1
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72