如何获取目录的父目录 [英] How can I go about getting the parent directory of a directory

查看:182
本文介绍了如何获取目录的父目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取目录的父目录?

How can I go about getting the parent directory of a directory?

File parent = new File("");
System.out.println("Parent directory : " + parent.getParent());

打印父目录:null

我有一个Maven多模块项目,想要转到父文件夹,然后回到每个模块文件夹和子文件夹中,获取其中的所有罐子。

I have a Maven multi-module project and would like to go to the parent folder then get back into each of the module folders and sub-folders getting all the jars in them.

parent  
    distributor  
        src.controllers  
            Dist.java  
    module1  
        src.controllers  
            1App.java  
        target  
            module1-1.0-SNAPSHOT.jar-  
    module2  
        src.controllers  
            2App.java  
        target  
            module2-1.0-SNAPSHOT.jar-  

上面,我来自Dist.java到 parent 然后进入 module1 module2

Above, I wold get from Dist.java to parent then into module1 and module2

推荐答案

引用 File.getParent() (强调我的):

Quoting javadoc of File.getParent() (emphasis mine):


返回此抽象路径名的父级的路径名字符串,如果此路径名未指定父目录,则返回 null

Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.

抽象路径名的包含路径名的前缀(如果有),以及路径名的名称序列中的每个名称(除了最后一个)。如果名称序列为空,则路径名不会命名父目录。

The parent of an abstract pathname consists of the pathname's prefix, if any, and each name in the pathname's name sequence except for the last. If the name sequence is empty then the pathname does not name a parent directory.

请记住,文件 object表示路径 string ,而不是文件系统上的实际文件。字符串没有父级。字符串a / b / ca / b作为父母,即使他们不在物理上存在。

Remember, a File object represent the path string, not an actual file on the file system. The string "" does not have a parent. The string "a/b/c" has "a/b" as the parent, even if they don't physically exist.

因此,首先你必须通过调用<将路径解析为真实路径code> getCanonicalFile()。 然后你可以找到父目录。

So, first you have to resolve the path "" to a real path by calling getCanonicalFile(). Then you can find the parent directory.

File file = new File("").getCanonicalFile();
System.out.println("Parent directory : " + file.getParent());

这篇关于如何获取目录的父目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆