2010-09-07 28 views

回答

126

无论哪种情况,我都希望file.getParent()(或file.getParentFile())能够给你想要的东西。

此外,如果你想找出原File是否确实存在一个目录,然后exists()isDirectory()是你追求的。

+7

使用file.getParent()小心,因为它可能会返回在某些情况下空。 – geschema 2014-07-22 09:02:44

+0

@geschema Ponaguynik的回答如下: – 4myle 2017-06-13 19:27:05

21

File.getParent()从Java文档

+0

It 404s *填充文本* – Caelum 2015-08-15 20:17:23

+0

https://docs.oracle.com/javase/8/docs/api/java/io/File.html#getParent-- – 2016-03-02 11:14:32

7

文件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 "); 
} 
4
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()); 
} 
+1

您不回答这个问题,这对文件不起作用。 – toni07 2015-04-06 21:17:29

+0

让我看看可重复的例子@toni – 2015-04-06 21:30:41

+0

'code' final File file = new File(“C:/dev/changeofseasons.mid”); System.out.println(“file exists?”+ file.exists()); System.out.println(“file of directory:”+ file.getAbsolutePath()); 好吧,对不起,缩进缩进,我不认为有可能在评论中格式化代码。不过,你的代码显然不起作用。 – toni07 2015-04-06 21:41:22

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

描述是必要的。 – 2015-03-03 11:08:01

+1

欢迎来到Stack Overflow!一般来说,代码的答案需要一点解释 - 看到这个元[Stackoverflow post](http://meta.stackoverflow.com/a/260413/838992)。有了你发布的答案,你可能需要解释你正在试图给出一个一般情况,以及它如何与OP的实际职位相关联。更严重的是,你可能想考虑它对'your_file_path =“C:\\ testfiles \\ temp \\ testfile”是如何工作的;' - 我不认为它会给你所希望的。 – 2015-03-03 12:54:18

+0

应该是正确答案。这将显示文件的完整路径。 – 2015-07-06 14:11:20

0

您可以使用此目录

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

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

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

如果你做这样的事情:

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

parent将是无效的。

因此,要获得该文件的目录,你接下来可以做的:

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

这将是我的解决方案

相关问题