How do I get a file's directory using the File object?
Consider the code:
File file = new File("c:\\temp\\java\\testfile");
testfile
is a file, and it may or may not exist.
I want to get the directory c:\\temp\\java\\
using the File
object. How do I go about doing this?
In either case, I'd expect file.getParent()
(or file.getParentFile()
) to give you what you want.
Additionally, if you want to find out whether the original File
does exist and is a directory, then exists()
and isDirectory()
are what you're after.
File.getParent() from Java Documentation
If you do something like this:
File file = new File("test.txt");
String parent = file.getParent();
parent
will be null.
So to get directory of this file you can do next:
parent = file.getAbsoluteFile().getParent();
File API File.getParent or File.getParentFile should return you Directory of file.
Your code should be like :
File file = new File("c:\\temp\\java\\testfile");
if(!file.exists()){
file = file.getParentFile();
}
You can additionally check your parent file is directory using File.isDirectory API
if(file.isDirectory()){
System.out.println("file is directory ");
}
File filePath=new File("your_file_path");
String dir="";
if (filePath.isDirectory())
{
dir=filePath.getAbsolutePath();
}
else
{
dir=filePath.getAbsolutePath().replaceAll(filePath.getName(), "");
}