java 如何在Java中拆分文件系统路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10228338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split filesystem path in Java?
提问by Jeegar Patel
If I have a string variable inside one class
如果我在一个类中有一个字符串变量
MainActivity.selectedFilePath
which has a value like this
它具有这样的值
/sdcard/images/mr.32.png
and I want to print somewhere only the path up to that folder without the filename
我想在某处只打印到该文件夹的路径,而没有文件名
/sdcard/images/
回答by codaddict
回答by Kai
String string = "/sdcard/images/mr.32.png";
int lastSlash = string.lastIndexOf("/");
String result = string.substring(0, lastSlash);
System.out.println(result);
回答by npe
new File(MainActivity.selectedFilePath).getParent().getAbsolutePath()
新文件(MainActivity.selectedFilePath).getParent().getAbsolutePath()
回答by Averroes
Create a File object with that path and then use getPath method from File Class.
使用该路径创建一个 File 对象,然后使用File Class 中的getPath 方法。
回答by Dani
String realPath = "/sdcard/images/mr.32.png";
String myPath = realPath.substring(0, realPath.lastIndexOf("/") + 1);
回答by sathya
final String dir = System.getProperty("user.dir");
String[] array = dir.split("[\\/]",-1) ;
String arrval="";
for (int i=0 ;i<array.length;i++)
{
arrval=arrval+array[i];
}
System.out.println(arrval);
回答by Qkyrie
- Files
- 文件
If the Files actually exist on the box, you could wrap the Strings up in a File object and call File.getParent().
如果文件实际上存在于盒子上,您可以将字符串包装在一个 File 对象中并调用File.getParent()。
- String.split()
- 字符串.split()
If the files don't exist, you could use the String.split() function to split the String with "/" as delimiter. You could then drop the last String in the array and rebuild it. This approach is rather dirty though.
如果文件不存在,您可以使用 String.split() 函数将字符串拆分为“/”作为分隔符。然后您可以删除数组中的最后一个字符串并重建它。虽然这种方法相当肮脏。
- Regular expressions
- 常用表达
You could use regular expressions to replace the part after the last / with "".
您可以使用正则表达式将最后一个 / 之后的部分替换为“”。
回答by Erick de Oliveira Santos
try this :
试试这个 :
File file = new File("path");
File file = new File("path");
parentPath = file.getParent();
parentPath = file.getParent();
parentDir = file.getParentFile();
parentDir = file.getParentFile();
回答by DGomez
You can use String.lastIndexOf(int ch);
which gives you the last occurrense of the character ch
您可以使用String.lastIndexOf(int ch);
which 为您提供字符 ch 的最后一次出现
回答by kundan bora
Here is the solution -
这是解决方案 -
String selectedFilePath= "/sdcard/images/mr.32.png";
selectedFilePath=selectedFilePath.substring(0,selectedFilePath.lastIndexOf("/"));
System.out.println(selectedFilePath);