1

I have various urls like this:

String a = "file:./bla/file.txt"; // Valid, see See [RFC 3986][1], path - rootless definition
String b = "file:.file.txt";      // Valid, see See [RFC 3986][1], path - rootless definition
String c = "file:./file.txt";     // Valid, see See [RFC 3986][1], path - rootless definition
String d = "file:///file.txt";
String e = "file:///folder/file.txt";
String f = "http://example.com/file.txt";
String g = "https://example.com/file.txt";

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

URL url = new URL(...);

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

file.txt

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

b.substring(path.lastIndexOf('/') + 1); // Returns file:.file.txt

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

4
  • You can use Path.of(urlstring).getFileName(); Commented Nov 17, 2021 at 19:32
  • @MirekPluta Thanks, but that doesn't work for example b Commented Nov 17, 2021 at 19:35
  • Even URI class fails to parse it. It cannot be proper URI, otherwise you found bug in JDK Commented Nov 17, 2021 at 19:45
  • 1
    Wouldn't example b represent a hidden file in the current directory? ie ./.file.txt I wouldn't expect the file name to be file.txt Commented Nov 17, 2021 at 21:14

1 Answer 1

4

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:

URI uri = new URI(b);
String path = uri.getPath();
if (path == null) {
    path = uri.getSchemeSpecificPart();
}
String filename = path.substring(path.lastIndexOf('/') + 1);

The above should work for all of your URLs.

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

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.