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.

Eric Tobias
  • 3,123
  • 4
  • 30
  • 49
Amrutha
  • 565
  • 4
  • 8
  • 28

5 Answers5

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?

Community
  • 1
  • 1
Pankaj Kumar
  • 81,071
  • 26
  • 167
  • 187
4

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

String[] parts = imagepath.split("/");
String result = parts[parts.length-1];
M.Sameer
  • 3,002
  • 1
  • 26
  • 37
4
String s[] = imgpath.split("/");
String result = s[s.length-1];
M.Sameer
  • 3,002
  • 1
  • 26
  • 37
Shivang Trivedi
  • 2,192
  • 1
  • 19
  • 26
1
String imgName = imgpath.substring((imgpath.lastIndexOf("/") + 1), imgpath.length());
vish
  • 168
  • 2
  • 13
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.

ppeterka
  • 20,372
  • 6
  • 62
  • 77