Arya
Arya

Reputation: 8985

extracting filename with extension form URL

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.

Upvotes: 1

Views: 97

Answers (6)

Hello World
Hello World

Reputation: 983

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);

Upvotes: 0

WearFox
WearFox

Reputation: 293

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

Upvotes: 0

Jeff Ward
Jeff Ward

Reputation: 1119

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.

Upvotes: 1

suneetha
suneetha

Reputation: 827

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());

Upvotes: 0

Syl OR
Syl OR

Reputation: 127

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

Upvotes: 0

Surendheran
Surendheran

Reputation: 197

Try,

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

Upvotes: 0

Related Questions