How do I split the file path to get the file name?

I have this line in my android app:

/storage/emulated/0/temp.jpg

      

I need to manipulate the string and split the string for this output:

temp.jpg

      

I always need to take the last element of the string.

How do I do this in java?

I would really appreciate any help you can give me on this issue.

+3


source to share


5 answers


one possibility:



String lStr = "/storage/emulated/0/temp.jpg";
lStr = lStr.substring(lStr.lastIndexOf("/"));
System.out.println(lStr);

      

+3


source


This is not an exercise for splitting lines

If you need to get the filename from the file path , use the File

class:

File f = new File("/storage/emulated/0/temp.jpg");
System.out.println(f.getName());

      



Output:

temp.jpg
+8


source


You can do this with a split string: How to split a string in Java

String string = "/storage/emulated/0/temp.jpg";
String[] parts = string.split("/");
String file= parts[parts.length-1]; 

      

+1


source


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 String split function. It splits the string into your input and returns an array of strings. Just access the last element of the array in your case.

0


source


Try the following:

String path= "/storage/emulated/0/temp.jpg";
String[] parts = path.split("/");
String filename;
if(parts.length>0)
    filename= parts[parts.length-1];  

      

0


source







All Articles