Java 如何拆分文件路径以获取文件名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26019132/
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 a file path to get the file name?
提问by Antonio Mailtraq
I have this string in my Android Application:
我的 Android 应用程序中有这个字符串:
/storage/emulated/0/temp.jpg
I need manipulate the string and to split the string for this output:
我需要操作字符串并为此输出拆分字符串:
temp.jpg
I need always take the last element of the string.
我需要总是取字符串的最后一个元素。
How to this output in java?
如何在java中输出?
I would greatly appreciate any help you can give me in working this problem.
我将不胜感激您在解决此问题时能给我的任何帮助。
采纳答案by Stefan Beike
one another possibility:
另一种可能性:
String lStr = "/storage/emulated/0/temp.jpg";
lStr = lStr.substring(lStr.lastIndexOf("/"));
System.out.println(lStr);
回答by arlistan
You can do it with string split: How to split a string in Java
您可以使用字符串拆分来实现:如何在 Java 中拆分字符串
String string = "/storage/emulated/0/temp.jpg";
String[] parts = string.split("/");
String file= parts[parts.length-1];
回答by brso05
String string = "/storage/emulated/0/temp.jpg";
String[] splitString = null;
splitString = string.split("/");
splitString[splitString.length - 1];//this is where your string will be
Try using the String function split. It splits the string by your input and returns an array of strings. Just access the last element of the array in your case.
尝试使用 String 函数 split。它根据您的输入拆分字符串并返回一个字符串数组。在您的情况下,只需访问数组的最后一个元素。
回答by Duncan Jones
回答by Jatin
Try this:
尝试这个:
String path= "/storage/emulated/0/temp.jpg";
String[] parts = path.split("/");
String filename;
if(parts.length>0)
filename= parts[parts.length-1];