Table of contents

Get basename from path or url string in Java

Java Feb 21, 2021 Viewed 33 Comments 0

Example

Get basename from path or url string. Follow these steps as bellow:

  • Remove characters after ? .
  • Remove characters before the last path separator. The path separator for Windows systems is \, and / for 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);
    }
}

Usage

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
}
Updated Feb 21, 2021