String getParent()
描述 (Description)
如果此抽象路径名为parent,则java.io.File.getParent()方法返回路径名字符串;如果此路径名未指定父目录,则返回null。
声明 (Declaration)
以下是java.io.File.getParent()方法的声明 -
public String getParent()
参数 (Parameters)
NA
返回值 (Return Value)
此方法返回此抽象路径名指定的父目录的路径名字符串,如果路径名未指定父路径,则返回null。
异常 (Exception)
NA
例子 (Example)
以下示例显示了java.io.File.getParent()方法的用法。
package com.iowiki;
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:\