0

I am working on android application. I am getting the image from gallery. Also I am getting the image path from gallery. Now my requirement is I want to get only the image name with the extension . How can I do that? Please help me.

String imgpath = "/mnt/sdcard/joke.png"; 

The image extension can be anything joke.png or joke.jpeg. I need to get the image name with extension finally.

i.e I want to split the above string and get only joke.png.

How can I achieve that? Please help me in this regard.

2

5 Answers 5

14
String imgpath = "/mnt/sdcard/joke.png"; String result = imgpath.substring(imgpath.lastIndexOf("/") + 1); System.out.println("Image name " + result); 

Output :-

Image name joke.png 

You should read How do I get the file name from a String containing the Absolute file path?

Sign up to request clarification or add additional context in comments.

Comments

4

You can do that in Android like in any Java program:

String[] parts = imagepath.split("/"); String result = parts[parts.length-1]; 

Comments

4
String s[] = imgpath.split("/"); String result = s[s.length-1]; 

Comments

1
String imgName = imgpath.substring((imgpath.lastIndexOf("/") + 1), imgpath.length()); 

Comments

0

You can get this with Regex too, if that is the hammer you have in your hands:

String fileName = null; Pattern pattern = Pattern.compile("(^|.*/)([^/]*)$"); Matcher m = pattern.getMatcher(filenameWithPath); if(matcher.matches()) { fileName = matcher.group(2); } 

But don't be tempted to do this. This is less readable, and probably even slower than the other methods.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.