Android Path to File Name Convert extractFolderOrFilename(String path)

Here you can find the source of extractFolderOrFilename(String path)

Description

extract Folder Or Filename

Parameter

Parameter Description
path to extract the file or folder name from

Return

null if not found or if path is null

Declaration

public static String extractFolderOrFilename(String path) 

Method Source Code

//package com.java2s;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    /**/*from w w  w .  jav  a 2 s.  c  o m*/
     * 
     * @param path to extract the file or folder name from
     * @return null if not found or if path is null
     */
    public static String extractFolderOrFilename(String path) {
        return regexExtract(path, "[^/]*$");
    }

    /**
     * Extracts regex match from string
     * @param string to search
     * @param pattern regex pattern
     * @return matched string, or null if nothing found (or null if any of the parameters is null)
     */
    public static String regexExtract(String string, String pattern) {
        if (string == null || pattern == null) {
            return null;
        }

        Matcher m = regexGetMatcherForPattern(string, pattern);
        if (m == null) {
            return null;
        }

        if (m.find()) {
            return m.group(0);
        } else
            return null;
    }

    public static Matcher regexGetMatcherForPattern(String string,
            String pattern) {
        if (string == null || pattern == null) {
            return null;
        }

        /**
         * strip newline characters because it doesn't work well with this.
         */
        //    string = string.replace("\n", "");

        Pattern p = Pattern.compile(pattern, Pattern.DOTALL
                | Pattern.MULTILINE);
        Matcher m = p.matcher(string);

        return m;
    }
}

Related

  1. getFileNameIndexFromPath(String filePathName)
  2. getFilename(String path)
  3. getShortFileName(String fullFileName)
  4. getFileName(String path)