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)
?
Why it is not suggested to pass hardcoded absolute path name to File object constructor File(String)
6.1k views Asked by AudioBubble At
2
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.