Java.io.File.getParent() Method
Advertisements
Description
The java.io.File.getParent() method returns the pathname string if this abstract path name's parent or null if this pathname does not name a parent directory.
Declaration
Following is the declaration for java.io.File.getParent() method:
public String getParent()
Parameters
NA
Return Value
This method returns pathname string of the parent directory named by this abstract pathname, or null if the pathname does not name a parent.
Exception
NA
Example
The following example shows the usage of java.io.File.getParent() method.
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();
}
}
}
Let us compile and run the above program, this will produce the following result:
parent name: C:\