[英]Cut variable path in java
For example I have this Path: 例如,我有以下路径:
C:\Program Files\7-Zip\7z.exe
Now I only want the Path but not the .exe like this: 现在我只想要路径,而不是像这样的.exe:
C:\Program Files\7-Zip
How can I cut the last part out in dynamic paths with more or less directories or longer names at the end? 如何在动态路径中切掉最后一部分,在结尾处带有更多或更少的目录或更长的名称?
I tried playing around with indexOf()
and subString()
but I don't really get it to work. 我尝试使用indexOf()
和subString()
但是我并没有真正使用它。
try using Java's path API: 尝试使用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 https://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html
Use something like this: 使用这样的东西:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.