例如,我有这个路径:
C:\Program Files\7-Zip\7z.exe
现在我只想要路径而不是像这样的.exe:
C:\Program Files\7-Zip
如何在最后使用更多或更少目录或更长名称的动态路径中删除最后一部分?
我尝试过使用indexOf()
和subString()
,但我并没有真正开始工作。
尝试使用Java的路径API:
Path file = Paths.get("C:\\Program Files\\7-Zip\\7z.exe");
Path dir = file.getParent();
System.out.println(dir.toString());
https://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html
使用这样的东西:
String path = "C:\\Program Files\\7-Zip\\7z.exe";
String[] a = path.split(Pattern.quote(""));
String newpath = "";
for(int i = a.length-1; i > 0; i--) {
if(a[i].compareTo("\\") != 0) {
a[i] = "";
} else {
break;
}
}
for(int i = 0; i < a.length; i++) {
if(a[i].compareTo("") != 0) {
newpath += a[i];
}
}
System.out.println(newpath);