如何从Java支持file、http/https协议的URL中提取文件名
方案1:Java标准库实现(无第三方依赖,最稳健)
核心逻辑是依托Java内置的URI规范解析能力,自动适配RFC 3986定义的各类合法URL格式,无需手动处理字符串切割逻辑,完美覆盖你给出的所有测试场景:
import java.net.URI; import java.nio.file.Paths; public class FileNameExtractor { public static String extractFileName(String urlStr) throws Exception { URI uri = new URI(urlStr); String path = uri.getPath(); // 适配无斜杠的rootless路径场景 if (path == null || path.isBlank()) { path = uri.getSchemeSpecificPart(); } return Paths.get(path).getFileName().toString(); } public static void main(String[] args) throws Exception { String[] testCases = { "file:./bla/file.txt", "file:.file.txt", "file:./file.txt", "file:///file.txt", "file:///folder/file.txt", "http://example.com/file.txt", "https://example.com/file.txt" }; for (String testUrl : testCases) { System.out.println(extractFileName(testUrl)); // 所有用例输出均为file.txt } } }
方案2:Apache Commons IO工具类实现
如果项目已引入Apache Commons IO依赖,可直接调用工具类方法,代码更简洁:
import java.net.URI; import org.apache.commons.io.FilenameUtils; // 调用示例 String fileName = FilenameUtils.getName(new URI("file:.file.txt").getSchemeSpecificPart());
注意:该方案需要项目提前引入Commons IO依赖,无依赖场景优先使用方案1
内容的提问来源于stack exchange,提问作者rmf
相关产品推荐
相关产品推荐

