Java.io.File.getParent() 方法
描述
如果此抽象路径名是父目录,则 java.io.File.getParent() 方法返回路径名字符串;如果此路径名未命名父目录,则返回 null。
声明
以下是 java.io.File.getParent() 方法的声明 −
public String getParent()
参数
NA
返回值
此方法返回由此抽象路径名命名的父目录的路径名字符串,如果路径名未命名父目录,则返回 null。
异常
NA
示例
下面的例子展示了 java.io.File.getParent() 方法的使用。
package com.tutorialspoint;
import java.io.File;
public class FileDemo {
public static void main(String[] args) {
File f = null;
String v;
boolean bool = false;
try {
// create new file
f = new File("C:\\test.txt");
// get file name or directory name
v = f.getParent();
// true if the file path exists
bool = f.exists();
// if file exists
if(bool) {
// prints
System.out.print("parent name: "+v);
}
} catch(Exception e) {
// if any error occurs
e.printStackTrace();
}
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
parent name: C:\

