File Constructors Explanation

前端 未结 4 596
轮回少年
轮回少年 2021-02-05 06:23

I was unable to understand the following file constructors.

public File(String parent, String child) and 
public File(File parent, String child)

相关标签:
4条回答
  • 2021-02-05 07:01

    "The parent abstract pathname is taken to denote a directory, and the child pathname string is taken to denote either a directory or a file. " As specified on the API

    0 讨论(0)
  • 2021-02-05 07:12

    Parent will point to the Directory

    Child will be its Contents..

    0 讨论(0)
  • 2021-02-05 07:16

    Explanation

    The parent parameter is the parent directory of the child file name or relative file path.

    Where parent is a File instance, it is a directory file. Where parent is a String, it's simply that directory in pathname terms.


    Examples

    Consider the following partial file system:

    Documents
        Homework
        Classwork
        Tests
    

    Rather than declaring each new file with "Documents\Subdir", you can declare the Documents directory as a file, and use it as the parent File of the other File instances, like so:

    File documents = new File("Documents");
    File tests = new File("Documents/Tests"); // new File(String);
    
    File homework = new File(documents, "Homework"); // new File(File, String)
    
    File classwork = new File("Documents", "Classwork"); // new File(String, String)
    

    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.

    File settingsFile = new File(Environment.getProgramDirectory(), "settings.txt");
    
    0 讨论(0)
  • 2021-02-05 07:28

    Let's explain with some examples:

    Assuming that you have the following structure:

    /dir1
      dir11
    

    The constructor that you usually use new File("/dir1/dir11") is equivalent to

    new File("/dir1", "dir11") (constructor taking 2 String as arguments)

    and also equivalent to

    new File(new File("/dir1"), "dir11") (constructor using a File as first argument).

    0 讨论(0)
提交回复
热议问题