Java - File getParent() 方法



描述

Java File getParent() 方法返回此抽象路徑名的父路徑名字串,如果此路徑名未命名父目錄,則返回 null。

宣告

以下是 java.io.File.getParent() 方法的宣告:-

public String getParent()

引數

返回值

此方法返回此抽象路徑名命名的父目錄的路徑名字串,如果路徑名未命名父目錄,則返回 null。

異常

示例 1

以下示例演示了 Java File getParent() 方法的使用。我們建立了兩個 File 引用。然後我們使用當前目錄中不存在的 test.txt 建立一個 File 物件。然後我們使用 createNewFile() 方法建立了該檔案。現在使用 getAbsoluteFile() 方法獲取檔案,並使用 getParent() 方法獲取檔案的父目錄名稱並列印它。

package com.tutorialspoint;
import java.io.File;
public class FileDemo {
   public static void main(String[] args) {      
      File f = null;
      File f1 = null;
      String path = "";
      boolean bool = false;
      
      try {
         // create new files
         f = new File("test.txt");
         
         // create new file in the system
         f.createNewFile();
         
         // create new file object from the absolute path
         f1 = f.getAbsoluteFile();
         
         // returns true if the file exists
         bool = f1.exists();
         
         // returns name of parent of the file
         path = f1.getParent();
         
         // if file exists
         if(bool) {
         
            // prints the file
            System.out.print("Parent: " + path);
         }
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:-

Parent: F:\Workspace\Tester

示例 2

以下示例演示了 Java File getParent() 方法的使用。我們建立了一個 File 引用。然後我們使用提供的目錄中的 F:/test.txt 建立一個 File 物件。現在使用 getAbsoluteFile() 方法獲取檔案,並在使用 getParent() 方法獲取其名稱後列印其父目錄名稱。

package com.tutorialspoint;
import java.io.File;
public class FileDemo {
   public static void main(String[] args) {      
      File f = null;
      
      try {
         // create new files
         f = new File("F:/test.txt");         
    
         // get the file
         File f1 = f.getAbsoluteFile();
         
         // prints the parent of file
         System.out.println("Parent: "+f1.getParent());
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:-

Parent: F:\

示例 3

以下示例演示了 Java File getParent() 方法的使用。我們建立了一個 File 引用。然後我們使用提供的路徑中的 F:/test 目錄建立一個 File 物件。現在使用 getAbsoluteFile() 方法獲取目錄,並使用 getParent() 方法獲取其父目錄名稱。

package com.tutorialspoint;
import java.io.File;
public class FileDemo {
   public static void main(String[] args) {      
      File f = null;
      
      try {
         // create new files
         f = new File("F:/test");         
    
         // get the file
         File f1 = f.getAbsoluteFile();
         
         // prints the file parent name
         System.out.println("Parent Directory: "+f1.getParent());
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:-

Parent Directory: F:\
java_file_class.htm
廣告

© . All rights reserved.