在Java程式中,如何獲取檔案的父目錄或上級目錄?
以下範例顯示如何使用File
類的file.getParent()
方法獲取檔案的父目錄。
package com.yiibai;
import java.io.File;
public class ParentDirectory {
public static void main(String[] args) {
File file = new File("F:\\worksp\\javaexamples\\java_directories\\myfile.txt");
String strParentDirectory = file.getParent();
System.out.println("Parent directory is : " + strParentDirectory);
}
}
執行上面範例程式碼,得到以下結果 -
Parent directory is : F:\worksp\javaexamples\java_directories
範例-2
以下是Java中獲取檔案的父目錄或所在目錄的另一個範例。
package com.yiibai;
import java.io.File;
import java.util.Scanner;
public class ParentDirectory2 {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the file path: ");
String filePath = scanner.next();
File fileToTest = new File(filePath);
if (!fileToTest.isDirectory()) {
System.out.println("This is File");
System.out.println("Parent Folder of this file is :" + fileToTest.getParent());
} else {
System.out.println("This is Directory");
System.out.println("Parent Folder of this directory is :" + fileToTest.getParent());
}
}
}
執行上面範例程式碼,得到以下結果 -
Enter the file path:
F:\worksp\javaexamples\java_directories
This is Directory
Parent Folder of this directory is :F:\worksp\javaexamples