Returns the file extension from the file part of the URL. - Java Network

Java examples for Network:URL

Description

Returns the file extension from the file part of the URL.

Demo Code

/*/*from   w  w  w  .jav a  2  s . c  o  m*/
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
//package com.java2s;
import java.net.URL;

public class Main {
    /**
     * Returns the file extension from the file part of the URL.
     * The returned file extension include the leading '.' character.
     * <P>
     * For example: if the URL is http://www.sun.com/index.html, the 
     * returned file extension is ".html".
     *
     * @param url the specified URL
     * @return the file extension of the file part of the URL.
     */
    public static String getFileExtensionByURL(URL url) {
        String trimFile = url.getFile().trim();

        if (trimFile == null || trimFile.equals("") || trimFile.equals("/")) {
            return null;
        }

        int strIndex = trimFile.lastIndexOf("/");
        String filePart = trimFile.substring(strIndex + 1,
                trimFile.length());

        strIndex = filePart.lastIndexOf(".");
        if (strIndex == -1 || strIndex == filePart.length() - 1) {
            return null;
        } else {
            String fileExt = filePart
                    .substring(strIndex, filePart.length());

            return fileExt;
        }
    }
}

Related Tutorials