Java File getParent()方法及示例
getParent() 方法是File类的一部分。这个函数返回给定文件对象的Parent。该函数返回一个字符串对象,其中包含给定文件对象的Parent。如果抽象路径不包含任何Parent,则返回一个空字符串。
函数签名
public String getParent()
函数语法
file.getParent()
参数: 该函数不接受任何参数。
返回值: 该函数返回一个字符串值,它是给定文件对象的父对象。
下面的程序将说明getParent()函数的使用。
例1: 我们得到了一个文件对象,我们必须得到该文件对象的Parent。
// Java program to demonstrate the// use of getParent() 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 String Parent = f.getParent(); // Display the file Parent // of the file object System.out.println("File Parent : " + Parent); } catch (Exception e) { System.err.println(e.getMessage()); } }}
输出
File Parent : c:\users

例2: 我们得到了一个目录下的文件对象,我们必须得到该文件对象的父对象。
// Java program to demonstrate the// use of getParent() 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 String Parent = f.getParent(); // Display the file Parent // of the file object System.out.println("File Parent : " + Parent); } catch (Exception e) { System.err.println(e.getMessage()); } }}输出
File Parent : c:\users

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