从 Java URL 中提取文件名(文件:和 http/https 协议)?

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

我有这样的各种网址:

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

这些都是有效的 URLS,我可以将它们转换为 java 中的 URL 而不会出错:

URL url = new URL(...);

我想从上面的每个示例中提取文件名,所以我只剩下:

file.txt

我尝试了以下方法,但这不起作用,例如上面的 b(这是一个有效的 URL):

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

我可能会编写一些自定义代码来检查斜杠,只是想知道是否有更好更稳健的方法来做到这一点?

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

以上应该适用于您的所有网址。