Java Utililty Methods URL to File Name

List of utility methods to do URL to File Name

Description

The list of methods to do URL to File Name are organized into topic(s).

Method

FilegetFileFromUrl(String url, File base)
Create a file from a 'relative' file URL
try {
    if (!url.startsWith("file://.")) {
        java.net.URI fileURI = new java.net.URI(url);
        return new File(fileURI);
} catch (java.net.URISyntaxException urise) {
    throw new IllegalArgumentException("Bad URL, cannot process " + url);
return new File(base, url.substring("file://.".length()));
FilegetFileFromUrl(String urlPath)
get File From Url
if (validFileUrl(urlPath)) {
    try {
        URL url = new URL(urlPath);
        try {
            return new File(url.toURI());
        } catch (Exception t) {
            return new File(url.getPath());
    } catch (MalformedURLException e) {
        return new File(urlPath);
return null;
FilegetFileFromURL(URL url)
get File From URL
return new File(url.toURI());
FilegetFileFromURL(URL url)
get File From URL
try {
    return new File(url.toURI());
} catch (URISyntaxException e) {
    throw new IllegalArgumentException(String.format("URL contains an invalid URI syntax: %s", url), e);
FilegetFileFromUrl(URL url)
get File From Url
File tmpImage = File.createTempFile("tesseract-ocr-download", null);
InputStream in = url.openConnection().getInputStream();
FileOutputStream fos = new FileOutputStream(tmpImage);
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) != -1) {
    fos.write(buf, 0, len);
fos.flush();
fos.close();
return tmpImage;
FilegetFileFromURL(URL urlToDecode)
Work-around for a bug/faulty design in getResource().getFile(), making space %20 etc
try {
    return new File(URLDecoder.decode(urlToDecode.getFile(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    return null;
StringgetFileName(final CharSequence url)
Returns the unqualified file name for the passed URL
return getFileName(toURL(url));
StringgetFileName(final URL url)
Returns with the file name (with the extension) extracted from the URL.
final String urlString = url.toString();
return urlString.substring(urlString.lastIndexOf('/') + 1, urlString.length());
StringgetFilename(final URL url)
Returns the text after the final / of a url.
int index = url.toString().lastIndexOf('/');
if (index < 0) {
    return url.toString();
} else {
    return url.toString().substring(index + 1);
StringgetFilename(final URL url, int maxLength)
get Filename
String filename = url.toString();
int index = filename.lastIndexOf('/');
if (index >= 0) {
    filename = filename.substring(index + 1);
if (maxLength > 0 && filename.length() > maxLength) {
    filename = filename.substring(filename.length() - maxLength);
return filename;