Skip to content
Advertisement

Extract file name from Java URL (file: and http/https protocol)?

I have various urls like this:

JavaScript

These are all valid URLS, and I can convert them to a URL in java without errors:

JavaScript

I want to extract the filename from each of the examples above, so I’m left with just:

JavaScript

I have tried the following, but this doesn’t work for example b above (which is a valid URL):

JavaScript

I can prob write some custom code to check for slashes, just wondering if there a better more robust way to do it?

Advertisement

Answer

The URI class properly parses the parts of a URI. For most URLs, you want the path of the URI. In the case of a URI with no slashes, there won’t be any parsing of the parts, so you’ll have to rely on the entire scheme-specific part:

JavaScript

The above should work for all of your URLs.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement