Java File getParentFile()方法及示例
getParentFile() 方法是File类的一个组成部分。这个函数返回给定文件对象的父文件。该函数返回一个文件对象,其中包含给定文件对象的父文件。如果抽象路径不包含任何Parent文件,那么将返回一个空值。
函数签名
public File getParentFile()
函数语法
file.getParentFile()
参数: 该函数不接受任何参数。
返回值: 该函数返回 File 对象,该对象是给定 File 对象的父文件。
下面的程序将说明getParentFile()函数的用途。
例1: 我们得到了一个文件对象,我们必须得到该文件对象的父文件。
// Java program to demonstrate the// use of getParentFile() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File("c:\\users\\program.txt"); // Get the Parent of the given file f File Parent = f.getParentFile(); // Display the file Parent file // of the file object System.out.println("File Parent : " + Parent.getPath()); } catch (Exception e) { System.err.println(e.getMessage()); } }}
输出
File Parent : c:\users

例2: 我们得到了一个目录下的文件对象,我们必须得到该文件对象的父文件。
// Java program to demonstrate the// use of getParentFile() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File("c:\\users\\program"); // Get the Parent of the given file f File Parent = f.getParentFile(); // Display the file Parent // file of the file object System.out.println("File Parent : " + Parent.getPath()); } catch (Exception e) { System.err.println(e.getMessage()); } }}产出 。
File Parent : c:\users

这些程序可能无法在在线IDE中运行。请使用离线IDE并设置文件的父文件
