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)
Asked
Active
Viewed 5,988 times
3
-
5Because the moment you use the code somewhere else, that file probably won't be there in that particular folder. – EpicPandaForce Jun 11 '15 at 08:57
-
Presuming that the file system structure remains same across different platforms wherever the code might get ported, is it more safe to use the File(String parent, String child) constructor, or will this also be flagged as potential defect ? – Jun 11 '15 at 09:09
-
*Is* it suggested? Where? What's the basis for your claim? – user207421 Jun 11 '15 at 09:43
-
If we use the File(String pathName) constructor 10 times in a program, then there would be 10 static analysis defects for the same reason. This number can be reduced from 10 to just 1 if we only use File(String pathName) for our first File Object and then use File(File parent, String child) for remaining. – Jun 11 '15 at 17:07
-
'static analysis defects' aren't part of the Java Language Specification or the Javadoc, which are the only normative references. They come out of some tool that you haven't specified. These things are invariably over-picky. I don't use them. – user207421 Jun 11 '15 at 23:17
2 Answers
3
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.

Mureinik
- 297,002
- 52
- 306
- 350
1
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.

sid
- 11
- 3