获取路径的路径,当前类文件
问题描述:
我想uptil两个目录的路径添加到当前类file.I上述路径的两个目录上面我用这样的:获取路径的路径,当前类文件
Test.class.getProtectionDomain().getCodeSource().getLocation().getPath()
,但只给出了路径当前类文件,而我想获得路径uptil父母的这个。 有没有任何干净的方式来获取这个没有使用子字符串?
答
如果从URL创建一个File
你可以调用它getParentFile()
:
URL fileUrl = Test.class.getProtectionDomain().getCodeSource().getLocation();
File file = new File(fileUrl.toURI);
String grandParent = file.getParentFile().getParent();
这也应该工作:
String grandParent = Test.class.getResource("../../").toString();
您可以添加''../将告诉操作系统从当前目录上升一级:'pathToCurrentDirectory +“../../”' – Leri