Java 从路径或者链接 url 字符串中获取文件名

Java 2021-02-18 阅读 5 评论 0

描述

从路径或者链接 url 的字符串中获取文件名,先删除 url 中 ? 后面的字符,也就是请求参数,再截取最后一个路径分隔符之后的部分,Windows 系统的分隔符为 \,Unix/Linux 分隔符为 /。实现的代码如下:

public class Filename {
    public String basename(String str) {
        if (str == null) {
            return "";
        }
        int questionIndex = str.indexOf("?");
        if (questionIndex != -1) {
            str = str.substring(0, questionIndex);
        }
        // The Unix separator character.
        char unixSeparator = '/';
        // The Windows separator character.
        char windowsSeparator = '\\';
        final int lastUnixPos = str.lastIndexOf(unixSeparator);
        final int lastWindowsPos = str.lastIndexOf(windowsSeparator);
        int lastIndex = Math.max(lastUnixPos, lastWindowsPos);
        return str.substring(lastIndex + 1);
    }
}

调用示例

public static void main(String args[]) {
    String url = "https://www.google.com/search/LRV_20210130_162218_11_014.insv?key=AADLg2BQJuGQQ06tGxJ-xQnJa&dl=0&preview=1";
    String path1 = "/Users/apple/Downloads";
    String path2 = "D:\\Downloads\\test.data";
    String path3 = "D:\\Downloads\\test";
    Filename filename = new Filename();
    System.out.println(filename.basename(url));     //  LRV_20210130_162218_11_014.insv
    System.out.println(filename.basename(path1));   //  Downloads
    System.out.println(filename.basename(path2));   //  test.data
    System.out.println(filename.basename(path3));   //  test
}
最后更新 2021-02-18