1

Let's say I have the following string

http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png

What would be the best way to extract b84.png from it? My program will be getting a list of image URLs and I want to extract the file name with its extension from each URL.

6 Answers 6

1

I would recommend using URI to create a File like this:

String url = "http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png";
URI uri = URI.create(url);
File f = new File(uri.getPath());

The uri.getPath() returns only the path portion of the url (i.e. removes the scheme, host, etc.) and produces this:

/photos/images/original/000/748/132/b84.png

You can then use the created File object to extract the file name from the full path:

String fileName = f.getName();
System.out.println(fileName);

Output of print statement would be: b84.png

However if you are not at all concerned by the input format of the url(s) then the substring answers are more terse. I figured I would offer an alternative. Hope it helps.

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

Comments

0

Try,

String url = "http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png";
String fileName = url.subString(url.lastIndexOf("/")+1);

Comments

0
String[] urlArray=yourUrlString.split("/");
String fileName=urlArray[urlArray.length-1];

Comments

0

I think, string lastIndexOf method is the best way to extract file name

String str = "http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png";
String result = str.substring(str.lastIndexOf('/')+1,str.length());

Comments

0

The method perfect for you

public String Name(String url){
        url=url.replace('\\', '/');
        return  url.substring(url.lastIndexOf('/')+1,url.length());
    }

this method returns any filename of any directory...whitout errors because convert the "\" to "/" so never will have problems with diferent directories

Comments

0

You can try this-

 String url = "http://i2.kym-cdn.com/photos/images/original/000/748/132/b84.png"
 url = url.substring(url.lastIndexOf("."));

If you don't png instead of .png, just change the last line to this-

 url = url.substring(url.lastIndexOf(".") + 1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.