文件构造函数说明 [英] File Constructors Explanation

查看:104
本文介绍了文件构造函数说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解以下文件构造函数。

I was unable to understand the following file constructors.

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

参数 parent 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)

我读过 java file docs 但我无法弄清楚何时以及如何使用这些构造函数。有人可以解释并举例说明。

I have read java file docs but I could not figure out when and how to use these constructors. Could someone please explain and give examples.

推荐答案

解释



parent 参数是文件名或相对文件路径的父目录。

Explanation

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

其中 parent 是一个File实例,它是一个目录文件。其中 parent 是一个String,它只是 pathname 条款中的那个目录。

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

考虑以下部分文件系统:

Consider the following partial file system:

Documents
    Homework
    Classwork
    Tests

您可以将Documents目录声明为文件,而不是使用Documents \Subdir声明每个新文件,并将其用作 parent 其他文件实例的文件,如下所示:

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应用程序



根据我的经验,我使用的应用程序提供的API包含一个方法,该方法返回允许第三方插件的目录文件保存/读取文件。如果没有文件(文件,字符串)构造函数,我需要将目录文件转换为绝对路径并将目标文件追加到它。


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.

在以下示例中, Environment.getProgramDirectory()返回授予权限的目录文件。

In the following example, Environment.getProgramDirectory() returns the directory file in which permissions are granted.

File settingsFile = new File(Environment.getProgramDirectory(), "settings.txt");

这篇关于文件构造函数说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆