如何使用File对象获取文件的目录?

122

考虑以下代码:

File file = new File("c:\\temp\\java\\testfile");

testfile 是一个文件,可能存在也可能不存在。 我想使用 File 对象获取目录 c:\\temp\\java\\。要如何实现?

10个回答

196

无论哪种情况,我都期望 file.getParent()(或者file.getParentFile())能够给你想要的结果。

此外,如果您想查找原始的File是否存在且是一个目录,则需要使用exists()isDirectory()方法。


12
请注意谨慎使用file.getParent(),因为在某些情况下它可能返回null。 - geschema
1
@geschema Ponaguynik在下面的回答中解决了这个问题。 - a113nw
这个(以及所有其他当前答案)在给定文件为例如new File("." + File.separator + ".")时,未能提供父目录(就文件系统而言)。如果需要更健壮的解决方案,请参见我下面的答案。 - Laike Endaril
System.out.println(new File("\myfile.txt").getParentFile().getAbsolutePath()); 正确地打印出 "C:",但是当你使用像这样的路径的 File 时要小心,因为一些写/读文件的库可能无法处理以反斜杠或 ".."(在理论上也是有效的)开头的路径。最好检查此处提到的所有可能性。这里 - Neph


26

如果你做类似这样的事情:

File file = new File("test.txt");
String parent = file.getParent();
< p > < code > parent 会是 null。

所以要获取此文件的目录,可以执行以下操作:

parent = file.getAbsoluteFile().getParent();

9

文件API File.getParent 或者 File.getParentFile 可以返回文件所在的目录。

你的代码应该像这样:

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

您可以使用File.isDirectory API检查您的父文件是否为目录。

if(file.isDirectory()){
    System.out.println("file is directory ");
}

3
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());
}

2
你没有回答问题,这对于文件不起作用。 - toni07
代码: final File file = new File("C:/dev/changeofseasons.mid"); System.out.println("文件是否存在?" + file.exists()); System.out.println("文件目录:" + file.getAbsolutePath());抱歉,缩进不太好看,我认为在评论中无法格式化代码。不过,你的代码显然无法运行。 - toni07

3
File filePath=new File("your_file_path");
String dir="";
if (filePath.isDirectory())
{
    dir=filePath.getAbsolutePath();
}
else
{
    dir=filePath.getAbsolutePath().replaceAll(filePath.getName(), "");
}

1
需要描述。 - Halvor Holsten Strand
2
欢迎来到Stack Overflow!一般来说,代码回答需要一些解释-请参阅此meta Stackoverflow post。对于您发布的答案,您可能需要解释您正在尝试提供一个通用情况以及它如何与OP的实际帖子相关。更严重的是-您可能需要考虑它在your_file_path = "C:\\testfiles\\temp\\testfile";上的工作方式-我认为它不会给出您所希望的结果。 - J Richard Snape

1
String parentPath = f.getPath().substring(0, f.getPath().length() - f.getName().length()); 

这将是我的解决方案。

0

2021年6月10日 如果给定的文件是...,所有当前的答案都会失败。

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());

请注意,本答案假定您想要“文件系统上实际的父目录”,而不是“表示给定文件对象的父节点的文件对象”(可能为null,或者与给定文件相同的目录)。
编辑:还要注意,内部文件名不够简洁,并且在某些情况下会随着重复使用而增长。一个等效的解决方案需要解析上述解决方案给出的完整绝对文件名,并调整输出,删除所有“。”和“..”的实例(后者当然需要在删除它之前也删除其前面的节点,但只有在删除所有“.”之后才能这样做)。

-1

你可以使用这个

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

-1

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接