繁体   English   中英

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

[英]How do I get a file's directory using the File object?

考虑代码:

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

testfile是一个文件,它可能存在也可能不存在。 我想使用File对象获取目录c:\\\\temp\\\\java\\\\ 我该怎么做?

在任何一种情况下,我都希望file.getParent() (或file.getParentFile() )给你你想要的。

此外,如果您想确定原始File是否确实存在并且一个目录,那么exists()isDirectory()就是您所追求的。

Java 文档中的File.getParent()

如果你做这样的事情:

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

parent将为空。

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

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

文件 API File.getParentFile.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 ");
}
File filePath=new File("your_file_path");
String dir="";
if (filePath.isDirectory())
{
    dir=filePath.getAbsolutePath();
}
else
{
    dir=filePath.getAbsolutePath().replaceAll(filePath.getName(), "");
}
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()); }
String parentPath = f.getPath().substring(0, f.getPath().length() - f.getName().length()); 

这将是我的解决方案

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

请注意,此答案假定您想要filesystem 上的实际父目录,而不是表示给定 File 对象的父节点的 File 对象(可能为空,也可能与给定文件位于同一目录)。

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

你可以用这个

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM