Java File类File getParentFile()方法(带示例)
文件类文件getParentFile()
软件包java.io.File.getParentFile()中提供了此方法。
此方法用于返回给定文件对象的父文件。
此方法的返回类型为File(即,它返回给定文件对象的父文件,而父文件为File形式。
语法:
File getParentFile(){
}参数:
我们不会在File方法中将任何对象作为参数传递。
返回值:
此方法的返回类型为File,即如果给定的文件对象的父文件不存在,则返回给定文件对象的父文件,然后以字符串形式返回null。
Java程序演示getParentFile()方法示例
//导入File类,因为我们将使用File类方法
import java.io.*;
//导入Exception类,因为它可能会引发
//处理文件时出现异常
import java.lang.Exception;
public class GetParentFile {
public static void main(String[] args) {
try {
//指定文件的路径,我们使用双斜杠
//为Windows转义'\'字符序列
File file1 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\ myjava.txt");
File file2 = new File("myjava.txt");
//通过使用getParentFile()方法返回一个文件
//包含给定文件对象的父文件。
File parent_file1 = file1.getParentFile();
//通过使用getParentFile()方法返回null作为字符串
//因为没有给定文件对象的父文件。
File parent_file2 = file2.getParentFile();
//显示给定文件对象的父对象
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();
}
}
}输出结果
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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿