getparentfile
文件类文件getParentFile() (File Class File getParentFile())
This method is available in package java.io.File.getParentFile().
软件包java.io.File.getParentFile()中提供了此方法。
This method is used to return the parent file of the given file object.
此方法用于返回给定文件对象的父文件。
The return type of this method is File (i.e It returns the parent file of the given file object and parent file is in File form.
此方法的返回类型为File(即,它返回给定文件对象的父文件,而父文件为File形式。
Syntax:
句法:
File getParentFile(){
}
Parameter(s):
参数:
We don't pass any object as a parameter in the method of the File.
我们不会在File方法中将任何对象作为参数传递。
Return value:
返回值:
The return type of this method is File i.e. It returns the parent file of the given file object if parent file does not exist then it returns null as a string.
此方法的返回类型为File,即如果给定的文件对象的父文件不存在,则返回给定文件对象的父文件,然后以字符串形式返回null。
Java程序演示getParentFile()方法的示例 (Java program to demonstrate example of getParentFile() method)
// import the File class because we will use File class methods
import java.io.*;
// import the Exception class because it may raise an
// exception when working with files
import java.lang.Exception;
public class GetParentFile {
public static void main(String[] args) {
try {
// Specify the path of file and we use double slashes to
// escape '\' character sequence for windows otherwise
// it will be considerable as url.
File file1 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\ myjava.txt");
File file2 = new File("myjava.txt");
// By using getParentFile() method returns a File which
// contain the parent file of the given file object.
File parent_file1 = file1.getParentFile();
// By using getParentFile() method returns null as a string
// because there is no parent file of the given file object.
File parent_file2 = file2.getParentFile();
// Display the parent of the given file object
System.out.println("The parent of the given parent_file1 is :" + parent_file1);
System.out.println("The parent of the given parent_file2 is :" + parent_file2);
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output
输出量
D:\Programs>javac GetParentFile.java
D:\Programs>java GetParentFile
The parent of the given parent_file1 is :C:\Users\computer clinic\OneDrive\Articles
The parent of the given parent_file2 is :null
翻译自: https://www.includehelp.com/java/file-class-file-getparentfile-method-with-example.aspx
getparentfile