I was unable to understand the following file constructors.
public File(String parent, String child) and
public File(File parent, String child)
What do the parameters parent and child mean for the file? When can I use these? I have done few programs related to file but I have never used these. I usually use
public File(String pathname)
I have read Javadoc but I could not figure out when and how to use these constructors. Could someone please explain and give examples.
Explanation
The
parentparameter is the parent directory of thechildfile name or relative file path.Where
parentis a File instance, it is a directory file. Whereparentis a String, it’s simply that directory inpathnameterms.Examples
Consider the following partial file system:
Rather than declaring each new file with “Documents\Subdir”, you can declare the Documents directory as a file, and use it as the
parentFile of the other File instances, like so:Real-world application
In my experience, I’ve used applications that provide an API containing a method that returns the directory file in which third-party “plugins” are allowed to save/read files. Without the
File(File, String)constructor, I would need to convert the directory file into an absolute path and append my target file to it.In the following example,
Environment.getProgramDirectory()returns the directory file in which permissions are granted.