例如,我有这样的路径:
C:\Program Files\7-Zip\7z.exe
现在我只想要路径,而不是像这样的.exe:
C:\Program Files\7-Zip
我如何在动态路径中剪掉最后一部分,在后面有或多或少的目录或更长的名称?
我试着和indexOf()
和subString()
一起玩,但是我并没有真正地让它发挥作用。
发布于 2018-09-18 09:13:36
尝试使用Java的path 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
发布于 2018-09-18 09:18:53
使用这样的东西:
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);
https://stackoverflow.com/questions/52382967
复制相似问题