Issue
My project is located here:
D:/WorkSpace/PuzzleApp
but when I am calling
new File(".").getAbsolutePath();
I get:
D:\!Documents\Desktop\.
Why? And how to fix this?
I'm using Eclipse.
Solution
When you open File with relative path "." this path is relative to the current process' working directory.
Usually, the process working directory is inherited from the parent process (e.g. if you run your app with Terminal - the current terminal's working directory will be your process' working dir).
Using a relative path inside your application is considered a bad idea because you can not control this process' working directory. But using an absolute hardcoded path also goes with some problems and can't be called a good practice.
There are several ways to solve the issue:
- Use a path relative to some NOT hardcoded absolute path. This absolute path should be externalized to environment variables, properties files, etc.
//Getting the directory path from the external system variable
String myAbsoultePath = System.getenv("LOCAL_STORAGE_DIR");
- Use a path relative to your application root. It allows you to READ files even located inside .jar or .war archives.
//This path looks absolute, but the path's root is your project's root
InputStream stream = MyClass.class.getResourceAsStream("/dir/another/file.txt");
But you should understand, that your application won't run inside your IDE project folder. It will be deployed in a production server/user's desktop/android device environment and usually, it is packed in a jar/war/ear/... archive. It means that you won't have access to your src folder or something like this.
Answered By - herman2lv
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.