Java.io.File.getParentFile() 方法

描述

java.io.File.getParentFile() 方法返回此抽象路径名的父级的抽象路径名,如果此路径名未命名父目录,则返回 null。


声明

以下是 java.io.File.getParentFile() 方法的声明 −

public File getParentFile()

参数

NA


返回值

此方法返回由此抽象路径名命名的父目录的抽象路径名,如果路径名未命名父目录,则返回 null。


异常

NA


示例

下面的例子展示了 java.io.File.getParentFile() 方法的使用。

package com.tutorialspoint;

import java.io.File;

public class FileDemo {
   public static void main(String[] args) {      
      File f = null;
      File f1 = null;
      String v;
      boolean bool = false;
      
      try {
         // create new file
         f = new File("C:\\test.txt");
         
         // returns abstract parent pathname
         f1 = f.getParentFile();
         
         // absolute path from abstract pathname
         v = f1.getAbsolutePath();
         
         // true if the file path exists
         bool = f.exists();
         
         // if file exists
         if(bool) {
         
            // prints
            System.out.print("Parent file path: "+v);
         }
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

让我们编译并运行上面的程序,这将产生下面的结果 −

Parent file path: C:\