Java URL to File Name getFileForUrl(URL url)

Here you can find the source of getFileForUrl(URL url)

Description

Return the File referenced by a "file:" or "jar:file:" URL.

License

Open Source License

Parameter

Parameter Description
url a URL; may be null

Return

the File this URL points to if applicable; otherwise null

Declaration

public static File getFileForUrl(URL url) 

Method Source Code

//package com.java2s;
// modify it under the terms of the GNU Lesser General Public License

import java.io.File;

import java.io.UnsupportedEncodingException;

import java.net.URL;
import java.net.URLDecoder;

public class Main {
    /**/*from w w  w . jav  a  2s  .co  m*/
     * Return the File referenced by a "file:" or "jar:file:" URL.
     * 
     * @param url
     *            a URL; may be null
     * @return the File this URL points to if applicable; otherwise null
     * @since 2.1.8
     */
    public static File getFileForUrl(URL url) {
        return (url == null ? null : getFileForUrl(url.toString()));
    }

    /**
     * Return the File referenced by a "file:" or "jar:file:" URL.
     * 
     * @param url
     *            a URL in string form; may be null
     * @return the File this URL points to if applicable; otherwise null
     * @since 2.1.8
     */
    public static File getFileForUrl(String url) {
        if (url == null)
            return null;

        if (url.startsWith("jar:")) {
            int pos = url.indexOf('!');
            url = (pos == -1 ? url.substring(4) : url.substring(4, pos));
        }

        String jarFileName;
        try {
            if (url.startsWith("file:"))
                jarFileName = URLDecoder.decode(url.substring(5), "UTF-8");
            else
                return null;
        } catch (UnsupportedEncodingException e) {
            // can't happen
            return null;
        }
        File jarFile = new File(jarFileName).getAbsoluteFile();
        return jarFile;
    }
}

Related

  1. getFileAbsoluteURL(String[] directoryPaths, String fileName)
  2. getFileDateTime(URL url)
  3. getFileExtensionByURL(URL url)
  4. getFileFor(URL url1)
  5. getFileForURL(String url)
  6. getFileFrom(final URL url)
  7. getFileFromUrl(String url, File base)
  8. getFileFromUrl(String urlPath)
  9. getFileFromURL(URL url)