mu_sa
mu_sa

Reputation: 2735

How to read file with different canonical paths

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

Upvotes: 0

Views: 570

Answers (3)

Amit Deshpande
Amit Deshpande

Reputation: 19185

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

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533870

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.

Upvotes: 0

jolivier
jolivier

Reputation: 7655

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 ;).

Upvotes: 1

Related Questions