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?

204505 次浏览

In either case, I'd expect file.getParent() (or file.getParentFile()) to give you what you want.

另外,如果您想知道原来的 File 是的是否存在,is是否是一个目录,那么 exists()isDirectory()就是您要找的。

文件 API File.getParent文件应该返回文件的目录。

你的代码应该是这样的:

    File file = new File("c:\\temp\\java\\testfile");
if(!file.exists()){
file = file.getParentFile();
}

您还可以使用 目录 API 检查父文件是否为目录

if(file.isDirectory()){
System.out.println("file is directory ");
}
File directory = new File("Enter any
directory name or file name");
boolean isDirectory = directory.isDirectory();
if (isDirectory) {
// It returns true if directory is a directory.
System.out.println("the name you have entered
is a directory  : "  +    directory);
//It returns the absolutepath of a directory.
System.out.println("the path is "  +
directory.getAbsolutePath());
} else {
// It returns false if directory is a file.
System.out.println("the name you have
entered is a file  : " +   directory);
//It returns the absolute path of a file.
System.out.println("the path is "  +
file.getParent());
}
File filePath=new File("your_file_path");
String dir="";
if (filePath.isDirectory())
{
dir=filePath.getAbsolutePath();
}
else
{
dir=filePath.getAbsolutePath().replaceAll(filePath.getName(), "");
}

你可以用这个

 File dir=new File(TestMain.class.getClassLoader().getResource("filename").getPath());

我发现这对于获得绝对文件位置更有用。

File file = new File("\\TestHello\\test.txt");
System.out.println(file.getAbsoluteFile());

如果你这样做:

File file = new File("test.txt");
String parent = file.getParent();

parent将为空。

因此,要获取这个文件的目录,接下来可以这样做:

parent = file.getAbsoluteFile().getParent();
String parentPath = f.getPath().substring(0, f.getPath().length() - f.getName().length());

这就是我的解决办法

6/10/2021 All current answers fail if eg. the given file is...

new File("." + File.separator + "."); //Odd, yes, but I've seen similar more often than you'd think is possible

为了得到一个简单而稳健的解决方案,请尝试..。

File givenFile = new File("." + File.separator + ".." + File.separator + "." + File.separator + "fakeFilename"); //The file or dir we want the parent of, whether it exists or not
File parentFile = new File(givenFile.getAbsolutePath() + File.separator + "..");
System.out.println(parentFile.getAbsolutePath());

Note that this answer assumes you want 文件系统上的实际父目录, and not 表示给定 File 对象的父节点的 File 对象 (which may be null, or may be the same directory as the given file).

编辑: 还要注意,内部文件名并不简洁,在某些情况下可能会随着重复使用而增长。没有这个问题的等价解决方案将需要解析上述解决方案给出的整个绝对文件名,并调整输出,删除“”的所有实例以及”。(后一个 ofc 也需要删除它之前的节点,但是只有在“之后”移除)