如何获得目录的父目录?
File parent = new File("");
System.out.println("Parent directory : " + parent.getParent());
印刷 Parent directory : null
我有一个Maven多模块项目,想转到父文件夹,然后回到每个模块文件夹和子文件夹中,获取其中的所有jar。
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到父级,然后进入module1和module2
引用File.getParent()
(强调我的)javadoc :
返回此抽象路径名的父级的路径名字符串,或者
null
如果此路径名未命名父目录,则返回该路径名字符串。抽象路径名的父级由路径名的前缀(如果有)以及路径名的名称序列中的每个名称(最后一个除外)组成。如果名称序列为空,则路径名不会命名父目录。
请记住,一个File
对象代表路径字符串,而不是文件系统上的实际文件。该字符串""
没有父代。即使字符串"a/b/c"
实际上"a/b"
不存在,它也具有作为父级的字符串。
因此,首先您必须""
通过调用将路径解析为真实路径getCanonicalFile()
。然后,您可以找到父目录。
File file = new File("").getCanonicalFile();
System.out.println("Parent directory : " + file.getParent());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句