Why it is not suggested to pass hardcoded absolute path name to File object constructor File(String)

6.1k views Asked by At

I am creating a File object in Java using File(String pathName), where pathName is the absolute path to the file. While this works perfectly fine from functionality point of view, but it frequently ends up as an static analysis defect. Is there any specific reason why it is suggested to use the constructor File(File parent, String child) over the File(String pathName)?

2

There are 2 answers

0
Mureinik On BEST ANSWER

As a general rule of thumb, hardcoding absolute paths makes your program less flexible. Consider a configuration file located at /usr/share/myapp/myapp.conf - what if the end user wants to install your application somewhere else than /usr/share? Using such an absolute path will break the application.

And as always, no general statement is true 100% of the time. If it makes absolutely no sense to have this file in any other location, just waive/suppress the warning in you static analysis tool.

0
sid On

In any of the application if we are using absolute path like D:\

If user don't have D: drive than application will be failed in creating folder .So we should not use absolute path. above is just an example to understand.