在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