Java File Name Extract extractFileName(String url)

Here you can find the source of extractFileName(String url)

Description

Extract the file name from the URL removing the scheme, domain, query params and named anchor, if present.

License

Apache License

Parameter

Parameter Description
url the URL to be used

Return

extracted filename from the URL

Declaration

public static String extractFileName(String url) 

Method Source Code

//package com.java2s;
/**//from  ww  w. ja  va 2 s.co m
 *
 * jerry - Common Java Functionality
 * Copyright (c) 2012-2015, Sandeep Gupta
 * 
 * http://sangupta.com/projects/jerry
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

public class Main {
    /**
     * Extract the file name from the URL removing the scheme, domain, query
     * params and named anchor, if present.
     * 
     * @param url
     *            the URL to be used
     * 
     * @return extracted filename from the URL
     */
    public static String extractFileName(String url) {
        int index1 = url.indexOf('?');
        int index2 = url.indexOf('#');

        if (index1 == -1) {
            index1 = url.length() + 1;
        }

        if (index2 == -1) {
            index2 = url.length() + 1;
        }

        int index = Math.min(index1, index2);
        if (index < url.length()) {
            url = url.substring(0, index);
        }

        index1 = url.lastIndexOf('/');
        index2 = url.lastIndexOf('\\');

        index = Math.max(index1, index2);

        url = url.substring(index + 1);

        return url;
    }
}

Related

  1. extractFileName(String path)
  2. extractFileName(String path)
  3. extractFilename(String path)
  4. extractFileName(String path)
  5. extractFilename(String path)
  6. extractFileNameFromBAMLocation(String location)
  7. extractFileNameFromContentDisposition(String contentDisposition)
  8. extractFileNameFromPath(final String filePath, char separatorChar)
  9. extractFileNameFromPath(final String path)